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?- A. 9 1
- B. 4 2
- C. 4 1
- 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
- Problem: Buy and sell a stock any number of times with a one-day cooldown after each sale. Maximise profit. python def cooldown(p): hold…
- Problem: Count the number of distinct ways to reach target t by putting + or − in front of every number. python from functools import…
- Problem: Generate all subsets of a set of feature flags (backtracking) and count those whose sum equals a target. python def count(a, t…
- Problem: Generate all permutations of a list that may contain duplicates, without repeats. How many are produced? python def perms(a)…
- Problem: Generate all valid strings of n pairs of brackets in lexicographic order of the recursion ('(' tried first). python def gen(n)…
- Problem: Count the ways to place n queens on an n × n board so none attack each other. python def queens(n): cols, d1, d2 = set(), set()…