← Meta (Facebook) bank

Meta (Facebook) · Question 68 · Dynamic Programming

Coin Change

Dynamic ProgrammingPythoncode⏱ O(amount*coins)💾 O(amount)
Product-based

Problem

You are given coins array and amount. Find minimum coins needed to make amount.

Approach

Unbounded knapsack: each coin relaxes every reachable amount.

Time O(amount*coins)Space O(amount)

How it works

  1. 1dp[a] holds the fewest coins for amount a.
  2. 2Unreachable amounts stay above amount: return -1.

Sample input / output

Input:
3 11
1 2 5
Output:
3

Constraints

1 <= coins.length <= 12; 0 <= amount <= 10^4.

Solution — read it, then walk it

Time O(amount*coins)Space O(amount)Loops 2Branches 2Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeatyesnoSTARTcoins, amountdp = [amount + 1] * (amount+ 1)dp[0] = 0for i in range(1,amount + 1)for coin in coinsif i >= coindp[i] = min(dp[i], dp[i -coin] + 1)RETURN dp[amount] ifdp[amount] <= amount else-1DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it)); amount =int(next(it))coins = [int(next(it)) for_ in range(n)]print(coinChange(coins,amount))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/18

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits