Skip to main content
12 of 15
added 310 characters in body
Jonathan Allan
  • 115.5k
  • 8
  • 68
  • 293

Largest rectangle in 2d array

Input

The board: A 2D container (matrix, list of lists, etc.) of letters like:

 ["B", "C", "C", "C", "C", "B", "B", "C", "A", "A"], ["B", "A", "C", "B", "B", "A", "B", "B", "A", "A"], ["B", "C", "B", "C", "A", "A", "A", "B", "C", "B"], ["B", "B", "B", "A", "C", "B", "A", "C", "B", "A"], ["A", "A", "A", "C", "A", "C", "C", "B", "A", "C"], ["A", "B", "B", "A", "A", "C", "B", "C", "C", "C"], ["C", "B", "A", "A", "C", "B", "B", "C", "A", "A"] 

If you choose a list of lists you may assume that all of the sublists are of the same length.

Rules

  • To make a valid rectangle you need all rectangle corners with the same 'letter'.
  • Example, look the sample board with X bellow. You can see 'X' on (1,0) also on (4,0) also on ( 1,3) and on (4,3) then you have the rectange [1,0,4,3] that means from (1,0) to (4,3):

Sample board with X:

 ["B", "X", "C", "C", "X", "B", "B", "C", "A", "A"], ["B", "A", "C", "B", "B", "A", "B", "B", "A", "A"], ["B", "C", "B", "C", "A", "A", "A", "B", "C", "B"], ["B", "X", "B", "A", "X", "B", "A", "C", "B", "A"], ["A", "A", "A", "C", "A", "C", "C", "B", "A", "C"], ["A", "B", "B", "A", "A", "C", "B", "C", "C", "C"], ["C", "B", "A", "A", "C", "B", "B", "C", "A", "A"] 
  • The goal is to found the "first" valid rectangle with the largest area
  • If there are multiple rectangles with the same maximum area, output one with (top coordinate, left coordinate, bottom coordinate, right coordinate) lexicographically smallest.
  • To calculate area for (1,0) to (4,3) you do (4-1)*(3-0).
  • Rectangles must have edges parallel to the board's edge.
  • The board has, at least, one non-zero area rectangle.
  • Each letter is a printable ASCII char from A to Z (both included).

Output

The output should be the left-up and right-down positions of the largest area rectangle corners. For the first sample "board" the big square is the yellow one:

enter image description here

And the answer should be:

[1, 1, 8, 4]

###A second example test case

An input of:

["C", "D", "D", "D", "A", "A"], ["B", "D", "C", "D", "A", "A"], ["B", "D", "D", "C", "A", "C"], ["B", "D", "B", "C", "A", "C"] 

Should yield

[1, 0, 2, 2]

(...not [1, 0, 3, 1] or [3, 2, 5, 3] both of which also have area six)

This question is posted on Stack Overflow with title: How to find the largest rectangle in a 2D array formed by four identical corners? and with this rude JS solution (I can say "rude" because is my code ;) :

Ok, is my first post, be tolerant with me please. I will change all you say to improve the quiz.

danihp
  • 361
  • 3
  • 7