Data Structures & AlgorithmsVery hardProduct company OA

Problem: Find the area of the largest all-'1' rectangle in a binary grid by treating each row as the base of a histogram and running the largest-rectangle-in-histogram stack on it.

Problem: Find the area of the largest all-'1' rectangle in a binary grid by treating each row as the base of a histogram and running the largest-rectangle-in-histogram stack on it.
def max_rect(grid):
    best = 0; h = [0] * len(grid[0])
    for row in grid:
        for j, c in enumerate(row):
            h[j] = h[j] + 1 if c == "1" else 0
        hh = h + [0]; st = []
        for j, x in enumerate(hh):
            while st and hh[st[-1]] >= x:
                top = st.pop()
                width = j if not st else j - st[-1] - 1
                best = max(best, hh[top] * width)
            st.append(j)
    return best
print(max_rect(["10111", "11111", "01110", "11110"]))
What is printed?
  1. A. 8
  2. B. 6
  3. C. 10
  4. D. 9

Correct answer: D. 9

h[j] is the number of consecutive 1s ending at the current row in column j. After the last row h = [1, 4, 3, 3, 0] (column 0 was broken by the 0 in row 2); the histogram's best rectangle is height 3 × width 3 over columns 1–3 = 9, i.e. rows 1–3, columns 1–3. The largest square (also 9 here) is a different problem in general, and 10 would need a 2 × 5 block, but row 0 has a 0 in column 1. O(R·C) total.

More Coding Interview Problems questions

Exams that ask this topic