Big O Gym › Problem

Big O Practice: Coin Change

Time and space complexity practice in Python and JavaScript. Concept tested: pseudopolynomial DP - value drives the cost.

def coin_change(coins, amount):
    dp = [amount + 1] * (amount + 1)
    dp[0] = 0
    for a in range(1, amount + 1):
        for c in coins:
            if a - c >= 0:
                dp[a] = min(dp[a], dp[a - c] + 1)
    if dp[amount] == amount + 1:
        return -1
    return dp[amount]

Variables

  • n - number of coin denominations
  • t - target amount

Explanation

The DP fills `t + 1` cells; for each cell it tries all `n` coins - **O(n ยท t)** total. The DP array has `t + 1` entries, **O(t)** space. The dominant variable is the target value, not the input length - a classic pseudopolynomial.

More Big O practice problems · Today's daily problem