2025-09-23 11:20
Status: adult
Tags: leetcode leetcode-medium strings arrays hash-maps google two-pointers sliding-window Leetcode
Fruit Into Baskets
Code
from collections import defaultdict
class Solution(object):
def totalFruit(self, fruits):
"""
:type fruits: List[int]
:rtype: int
"""
count = defaultdict(int)
res, l, total = 0, 0, 0
n = len(fruits)
for r in range(n):
count[fruits[r]] += 1
total += 1
while len(count) > 2:
left_fruit = fruits[l]
count[left_fruit] -= 1
total -= 1
l += 1
if not count[left_fruit]:
count.pop(left_fruit)
res = max(res, total)
return res
Explanation
-
It uses a two pointer approach(sliding window). The problem wants us to find the longest contiguous subarray with 2 distinct elements
-
Use a sliding window with two pointers (l and r).
-
Expand r: add the fruit to count, increase window size.
-
If window has >2 types, shrink from l until only 2 remain.
-
Update res with the max window length.
-
Return res.