Fruit Into Baskets

MediumSliding Windowsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A row of trees is described by fruits, where fruits[i] is the type of fruit growing on tree i. You carry two baskets, and each basket may hold any amount of fruit but only **one type**. Pick a starting tree and walk right, taking exactly one fruit from every tree you pass. You must stop as soon as a tree's fruit type would need a third basket (or when you run out of trees). Return the maximum number of fruits you can collect. Equivalently: the length of the longest contiguous subarray containing at most two distinct values.

Examples

Input: fruits = [1,2,1]
Output: 3
All three trees use only types 1 and 2.
Input: fruits = [0,1,2,2]
Output: 3
Start at index 1 and collect [1,2,2].
Input: fruits = [1,2,3,2,2]
Output: 4
Start at index 1 and collect [2,3,2,2].

Constraints

  • 1 <= fruits.length <= 10^5
  • 0 <= fruits[i] < fruits.length

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems