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?
  1. A. 4 4
  2. B. 9 4
  3. C. 4 9
  4. 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

Exams that ask this topic