Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Count the number of ways to make an amount from unlimited coins, where order does not matter.
Problem: Count the number of ways to make an amount from unlimited coins, where order does not matter.
def ways(cs, amt):
dp = [1] + [0] * amt
for c in cs:
for a in range(c, amt + 1):
dp[a] += dp[a - c]
return dp[amt]
def ordered(cs, amt):
dp = [1] + [0] * amt
for a in range(1, amt + 1):
for c in cs:
if c <= a: dp[a] += dp[a - c]
return dp[amt]
print(ways([1, 2, 5], 5), ordered([1, 2, 5], 5))What is printed?- A. 4 4
- B. 9 4
- C. 4 9
- D. 5 9
Correct answer: C. 4 9
Coins in the outer loop count combinations (each multiset once): 5, 2+2+1, 2+1+1+1, 1×5 → 4. Amounts in the outer loop count ordered sequences (compositions): 1+2+2, 2+1+2 and 2+2+1 are different, giving 9. Swapping the loops is the classic bug. Both O(amount × coins).
More Coding Interview Problems questions
- Problem: 0/1 knapsack with a 1-D array. The candidate below loops capacity upwards. python def wrong(w, v, W): dp = [0] (W + 1) for i in…
- Problem: 0/1 knapsack – maximise value within capacity W. cpp int knap(vector<int> w, vector<int> v, int W) { vector<int> dp(W + 1, 0)…
- Problem: Find the length of the longest strictly increasing subsequence of daily sales. python from bisect import bisectleft def lis(a)…
- Problem: Find the length of the longest common subsequence of two version strings. python def lcs(a, b): dp = [[0] (len(b) + 1) for in…
- Problem: Find the minimum number of insert, delete or replace operations to convert one word to another (edit distance). python def…
- Problem: Count paths from the top-left to the bottom-right of a grid moving only right or down, where 1 marks a blocked cell. python def…