Skip to content

Fruit Into Baskets

MediumPython 3Sliding windowArraysHash tables

You are walking down a row of fruit trees, given as a list fruits where fruits[i] is the type of fruit growing on tree i. You carry two baskets and each basket holds only one type of fruit (in unlimited quantity).

You pick exactly one fruit from every tree you visit, you must start at some tree and visit trees left to right without skipping any, and you stop as soon as you reach a tree whose fruit fits in neither basket.

Return the maximum number of fruits you can pick: the length of the longest contiguous subarray containing at most two distinct values.

Constraints:
  - 1 <= len(fruits) <= 10^5
  - fruit types are non-negative integers
Examples:
  [1, 2, 1]             -> 3   (the whole row uses two types)
  [0, 1, 2, 2]          -> 3   ([1, 2, 2])
  [1, 2, 3, 2, 2]       -> 4   ([2, 3, 2, 2])
  [3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4] -> 5   ([1, 2, 1, 1, 2])

Python 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.

Loading the editor…