MediumNo. 0322
Coin Change — LeetCode 322 Python Solution
- Pattern
- Breadth-First Search
- Topics
- Breadth-First Search, Array, Dynamic Programming
- On study lists
- Blind 75, NeetCode 150, Grind 75 and Top Interview 150
- 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
- Time
- O(m × n)
- Space · auxiliary
- O(m × n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0518 | Coin Change II | Medium |
| 0329 | Longest Increasing Path in a Matrix | Hard |
| 0542 | 01 Matrix | Medium |
| 0773 | Sliding Puzzle | Hard |
| 1162 | As Far from Land as Possible | Medium |
| 1654 | Minimum Jumps to Reach Home | Medium |
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 × n).
- What is the space complexity of LeetCode 322. Coin Change?
The Python solution on this page uses O(m × 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.