Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the largest square of 1s in a binary matrix and return its area.

Problem: Find the largest square of 1s in a binary matrix and return its area.
def square(m):
    R, C = len(m), len(m[0]); dp = [[0] * (C + 1) for _ in range(R + 1)]; best = 0
    for r in range(R):
        for c in range(C):
            if m[r][c] == 1:
                dp[r+1][c+1] = 1 + min(dp[r][c+1], dp[r+1][c], dp[r][c])
                best = max(best, dp[r+1][c+1])
    return best * best
print(square([[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]]), square([[0, 1], [1, 0]]))
What is printed?
  1. A. 9 1
  2. B. 4 2
  3. C. 4 1
  4. D. 6 1

Correct answer: C. 4 1

dp = side of the largest square ending at a cell = 1 + min(top, left, top-left). The best side is 2 (rows 1–2, columns 2–3), area 4. The 2 × 3 block of ones in rows 1–2 is a rectangle (area 6), not a square. The diagonal matrix has only 1 × 1 squares. O(R·C).

More Coding Interview Problems questions

Exams that ask this topic