Coin Change — LeetCode 322 Python Solution
- Problem
- #322
- Pattern
- Breadth-First Search
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount.
Example
- Input
- coins = [1,2,5], amount = 11
- Output
- 3
- Explanation
- 11 = 5 + 5 + 1
Python solution
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
m, n = len(coins), amount
f = [[inf] * (n + 1) for _ in range(m + 1)]
f[0][0] = 0
for i, x in enumerate(coins, 1):
for j in range(n + 1):
f[i][j] = f[i - 1][j]
if j >= x:
f[i][j] = min(f[i][j], f[i][j - x] + 1)
return -1 if f[m][n] >= inf else f[m][n]Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(m \times n) auxiliary |
Pattern: Breadth-First Search
Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 322. Coin Change is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.
The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 322. Coin Change?
- LeetCode 322. Coin Change is rated Medium on LeetCode.
- What is the time complexity of LeetCode 322. Coin Change?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 322. Coin Change?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 322. Coin Change cover?
- LeetCode 322. Coin Change is tagged Breadth-First Search, Array and Dynamic Programming on LeetCode.