#3679
Minimum Discards to Balance Inventory
MediumArrayHash TableSliding WindowSimulationCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a sliding window to efficiently track item counts and discard excess items without re-evaluating the entire window.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a count map and two pointers for the sliding window.
- 2Step 2: For each arrival, update the count and check if it exceeds m; if so, increment discard count.
- 3Step 3: Move the left pointer to maintain the window size and adjust counts accordingly.
solution.py12 lines
1def min_discards(arrivals, w, m):
2 from collections import defaultdict
3 discard_count = 0
4 counts = defaultdict(int)
5 left = 0
6 for right in range(len(arrivals)):
7 counts[arrivals[right]] += 1
8 while counts[arrivals[right]] > m:
9 counts[arrivals[left]] -= 1
10 left += 1
11 discard_count += 1
12 return discard_countℹ
Complexity note: Each arrival is processed once, maintaining a sliding window leads to O(n).
- 1Sliding window allows efficient management of counts.
- 2Using a hash map simplifies counting occurrences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.