#3116
Kth Smallest Amount With Single Denomination Combination
HardArrayMathBinary SearchBit ManipulationCombinatoricsNumber TheoryBinary SearchGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log(max(coins))) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n log(max(coins)))Space O(1)
Instead of generating all amounts, we can use binary search to find the k-th smallest amount by counting how many amounts can be formed up to a certain value using the coins.
⚙️
Algorithm
3 steps- 1Step 1: Define a function to count how many amounts can be formed up to x using the coins.
- 2Step 2: Use binary search to find the smallest x such that the count of amounts is at least k.
- 3Step 3: Return x as the k-th smallest amount.
solution.py16 lines
1def countAmounts(coins, x):
2 count = 0
3 for coin in coins:
4 count += x // coin
5 return count
6
7
8def kthSmallest(coins, k):
9 left, right = 1, 2 * 10**9
10 while left < right:
11 mid = (left + right) // 2
12 if countAmounts(coins, mid) < k:
13 left = mid + 1
14 else:
15 right = mid
16 return leftℹ
Complexity note: The time complexity is O(n log(max(coins))) due to the binary search over the range of possible amounts, where n is the number of coins. The space complexity is O(1) as we are only using a few variables.
- 1Understanding how to count distinct amounts is crucial for optimizing the solution.
- 2Binary search can significantly reduce the time complexity by narrowing down the search space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.