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?- A. 8
- B. 6
- C. 10
- 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
- Problem: Does a price series contain a '132' pattern – indices i < j < k with a[i] < a[k] < a[j]? Scan from the right with a decreasing…
- Problem: Delete repeated letters so each letter appears once, and among all such results return the lexicographically smallest (a…
- Problem: A game board has scores a[0..n−1]; from cell i you may jump forward 1..k cells. Starting at 0 and ending at n − 1, maximise the…
- Problem: A council of two parties, R and D, votes in rounds in seat order. On their turn a member bans the next opposing member who has…
- Problem: People stand in a line facing right with distinct heights. Person i can see person j > i if everyone strictly between them is…
- Problem: An employee's day is 'tiring' if they worked more than 8 hours. Find the longest run of consecutive days in which tiring days…