MediumNo. 0904
Fruit Into Baskets — LeetCode 904 Python Solution
- Pattern
- Sliding Window
- Topics
- Array, Hash Table, Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.
Example
- Input
- fruits = [1,2,1]
- Output
- 3
- Explanation
- We can pick from all 3 trees.
Python solution
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
cnt = Counter()
ans = j = 0
for i, x in enumerate(fruits):
cnt[x] += 1
while len(cnt) > 2:
y = fruits[j]
cnt[y] -= 1
if cnt[y] == 0:
cnt.pop(y)
j += 1
ans = max(ans, i - j + 1)
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(1)
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 904. Fruit Into Baskets is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0219 | Contains Duplicate II | Easy |
| 0480 | Sliding Window Median | Hard |
| 0594 | Longest Harmonious Subsequence | Easy |
| 0632 | Smallest Range Covering Elements from K Lists | Hard |
| 0930 | Binary Subarrays With Sum | Medium |
| 0992 | Subarrays with K Different Integers | Hard |
Frequently asked questions
- How hard is LeetCode 904. Fruit Into Baskets?
LeetCode 904. Fruit Into Baskets is rated Medium on LeetCode.
- What is the time complexity of LeetCode 904. Fruit Into Baskets?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 904. Fruit Into Baskets?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 904. Fruit Into Baskets cover?
LeetCode 904. Fruit Into Baskets is tagged Array, Hash Table and Sliding Window on LeetCode.