Skip to content

Commit 5d5df43

Browse files
Leetcode 904
1 parent 131fd59 commit 5d5df43

1 file changed

Lines changed: 83 additions & 0 deletions

File tree

Leetcode/Leetcode_904.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# 904. Fruit Into Baskets
2+
3+
## Approach: Sliding Window + Hash Map
4+
5+
We use a sliding window to maintain a contiguous subarray that contains at most **2 distinct fruit types**.
6+
7+
- Expand the window by moving the `right` pointer.
8+
- Store the frequency of fruits inside the current window using a hash map.
9+
- If the window contains more than 2 fruit types, shrink it from the left until only 2 types remain.
10+
- Track the maximum valid window length throughout the process.
11+
12+
## Code
13+
14+
```python
15+
class Solution:
16+
def totalFruit(self, fruits: List[int]) -> int:
17+
from collections import defaultdict
18+
19+
left = 0
20+
max_fruits = 0
21+
basket = defaultdict(int)
22+
23+
# Expand the window using the right pointer
24+
for right in range(len(fruits)):
25+
basket[fruits[right]] += 1
26+
27+
# Shrink the window if more than 2 fruit types exist
28+
while len(basket) > 2:
29+
basket[fruits[left]] -= 1
30+
31+
# Remove fruit type if its count becomes 0
32+
if basket[fruits[left]] == 0:
33+
del basket[fruits[left]]
34+
35+
left += 1
36+
37+
# Update the maximum valid window size
38+
max_fruits = max(max_fruits, right - left + 1)
39+
40+
return max_fruits
41+
```
42+
43+
## How It Works
44+
45+
### Example
46+
47+
```python
48+
fruits = [1, 2, 1, 2, 3]
49+
```
50+
51+
| Left | Right | Window | Distinct Fruits | Max Length |
52+
|--------|---------|---------------|----------------|------------|
53+
| 0 | 0 | [1] | 1 | 1 |
54+
| 0 | 1 | [1, 2] | 2 | 2 |
55+
| 0 | 2 | [1, 2, 1] | 2 | 3 |
56+
| 0 | 3 | [1, 2, 1, 2] | 2 | 4 |
57+
| 0 | 4 | [1, 2, 1, 2, 3] | 3 | Invalid |
58+
| 3 | 4 | [2, 3] | 2 | 4 |
59+
60+
The longest valid subarray containing at most 2 distinct fruit types is:
61+
62+
```python
63+
[1, 2, 1, 2]
64+
```
65+
66+
So the answer is:
67+
68+
```python
69+
4
70+
```
71+
72+
## Time Complexity
73+
74+
- Each fruit enters the window once and leaves the window once.
75+
- Therefore, both pointers traverse the array at most one time.
76+
77+
**Time Complexity:** `O(n)`
78+
79+
## Space Complexity
80+
81+
- The hash map stores at most 3 fruit types before shrinking the window.
82+
83+
**Space Complexity:** `O(1)`

0 commit comments

Comments
 (0)