Fruit Into Baskets — LeetCode 904 Python Solution

MediumArrayHash TableSliding Window
Problem
#904
Reading time
3 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview