Data Structures & AlgorithmsModerateAmazon · Microsoft OA

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

Problem: Find the area of the largest square of 1s in a binary matrix.
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]:
                dp[r+1][c+1] = 1 + min(dp[r][c], dp[r][c+1], dp[r+1][c])
                best = max(best, dp[r+1][c+1])
    return best * best
print(square([[1,0,1,1,1],[1,1,1,1,1],[0,1,1,1,1],[1,1,1,1,0]]))
What is printed?
  1. A. 9
  2. B. 3
  3. C. 16
  4. D. 6

Correct answer: A. 9

dp[r][c] is the side of the largest square ending at (r, c), limited by its top, left and top-left neighbours. A 3 × 3 block of 1s exists (rows 0–2, columns 2–4), but no 4 × 4, so the area is 9 (side 3 is the trap).

More Coding Interview Problems questions

Exams that ask this topic