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?- A. 9
- B. 3
- C. 16
- 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
- Problem: Length of the longest common CONTIGUOUS subarray of two arrays (DP on suffix matches). python def common(a, b): dp = [[0] (len(b)…
- Problem: A knight makes k uniformly random moves (8 directions) on an n × n board; once it leaves the board it stays off. What is the…
- Problem: Choose the largest number of binary strings using at most m zeros and n ones in total (2-D 0/1 knapsack). python def most(strs…
- Problem: Delete characters from two strings so they become equal, minimising the sum of ASCII codes deleted. python def cost(a, b): m, n =…
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Report (first player's total) − (second…
- Problem: Count the combinations (multisets) of candidates that sum to the target; each candidate may be used any number of times. python…