Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count all square submatrices made entirely of 1s.
Problem: Count all square submatrices made entirely of 1s.
def count(m):
R, C = len(m), len(m[0]); tot = 0
dp = [row[:] for row in m]
for r in range(R):
for c in range(C):
if m[r][c] and r and c:
dp[r][c] = 1 + min(dp[r-1][c], dp[r][c-1], dp[r-1][c-1])
tot += dp[r][c]
return tot
print(count([[0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1]]))What is printed?- A. 10
- B. 13
- C. 15
- D. 17
Correct answer: C. 15
dp[r][c] = side of the largest all-1 square ending at (r, c), and that cell also ends exactly dp[r][c] squares (sides 1..dp). The grid has 10 ones (10 squares of side 1), 4 squares of side 2 and 1 of side 3: 15.
More Coding Interview Problems questions
- Problem: Paint n fence posts with k colours so that no three consecutive posts share a colour. python def ways(n, k): same, diff = 0, k…
- Problem: A pointer starts at index 0 of an array of length n; each step it moves left, right or stays (never leaving the array). Count the…
- Problem: Trade a stock any number of times (one share at most), but after selling you must wait one day before buying again. python def…
- Problem: Wildcard matching where '?' matches one character and '' matches any sequence (including empty); the whole string must match…
- Problem: Count the ways to partition a string into substrings that are all palindromes. python def parts(s): n = len(s); dp = [1] + [0] n…
- Problem: Insert +, − or between the digits of num (or leave digits joined) so that the expression equals target. Count the expressions (no…