Skip to content

visual walkthrough

Fruit Into Baskets

MediumVariable Window + Frequency MapReported at: Amazon

Longest window with at most two distinct values, in disguise.

Solve on LeetCode

The idea

It's the longest subarray with at most two distinct values. A map of counts inside the window tells you how many types you hold.

When a third type enters, drop trees from the left until one type's count falls to zero.

Complexity

approachtimespace
Try every startO(n²)O(1)
Sliding windowO(n)O(1)

More walkthroughs