Back to Sliding Window
Sliding Window
Medium

Fruit Into Baskets

LAB

Return the length of the longest contiguous subarray containing at most two distinct values.

EXAMPLES

Example 1
Input
{
  "fruits": [
    1,
    2,
    1
  ]
}

Output
3

FUNCTION SHAPE

fruits: intArrayint
SOLUTION NOTE

This is exactly the same as Q340 with k = 2. Note: fruits is a list of ints, not a string, but you can easily adapt the template.

Reveal reference solution +
pythonREFERENCE
def totalFruit(self, fruits: List[int]) -> int:
    n, l, freq, res = len(fruits), 0, Counter(), 0

    for r in range(n):
        freq[fruits[r]] += 1

        while len(freq) > 2:
            freq[fruits[l]] -= 1
            if freq[fruits[l]] == 0: del freq[fruits[l]]
            l += 1

        res = max(res, r - l + 1)

    return res

# Or simply:
# return lengthOfLongestSubstringKDistinct(fruits, 2)
TimeO(n)
SpaceO(1)
Open on LeetCode
00:00
3 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.