Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the minimum number of perfect squares that sum to n.
Problem: Find the minimum number of perfect squares that sum to n.
def squares(n):
dp = [0] + [float('inf')] * n
for i in range(1, n + 1):
j = 1
while j * j <= i:
dp[i] = min(dp[i], dp[i - j * j] + 1); j += 1
return dp[n]
print(squares(12), squares(13), squares(7))What is printed?- A. 3 2 4
- B. 2 2 4
- C. 3 2 3
- D. 4 2 4
Correct answer: A. 3 2 4
12 = 4 + 4 + 4 (3), not the greedy 9 + 1 + 1 + 1 (4). 13 = 9 + 4. 7 = 4 + 1 + 1 + 1 needs 4, as Legendre's three-square theorem predicts for numbers of the form 8k + 7. O(n √n).
More Coding Interview Problems questions
- Problem: Count the number of distinct subsequences of s that equal t. python def distinct(s, t): dp = [1] + [0] len(t) for ch in s: for j…
- Problem: Find the longest increasing path in a matrix (moving up/down/left/right to strictly larger values). python from functools import…
- Problem: Find the cheapest way to cut a stick of length n at given positions; each cut costs the current piece's length. python from…
- Problem: Burst balloons; bursting balloon i earns left × a[i] × right with its current neighbours (1 beyond the ends). Maximise coins…
- Problem: Find the minimum number of intervals to remove so that the rest are non-overlapping – implemented with sort by START and keeping…
- Problem: Find the length of the longest valid (well-formed) parentheses substring. python def longestvalid(s): st, best = [-1], 0 for i…