Fruit Into Baskets
At-most-2-distinct sliding window
You have exactly 2 baskets, so at any time the current window may contain at most 2 distinct fruit types. Slide a window right, tracking counts of each type; the instant a 3rd distinct type would enter, shrink from the left until only 2 types remain. The longest window seen along the way is the answer — no need to restart from scratch each time.
Details
Animated on: fruits = [1,2,3,2,2] — find the longest run of trees you can pick from with only 2 baskets (2 distinct fruit types).
Problem:Fruit Into BasketsMedium
Pattern:Sliding Window
At-most-2-distinct sliding window
step 1 / 8
Add fruits[0]=1. Basket holds {1}. 1 distinct type — within the limit of 2.
- l=0· arr[0] = 1
- r=0· arr[0] = 1
1FUNCTION totalFruit(fruits):2 count = a table of fruit type -> how many are in the window; l = 0; maxLen = 03 FOR each right edge r from 0 to the end of fruits:4 add one to the count of fruits[r]5 WHILE the table holds more than 2 distinct types:6 remove one fruits[l] from the count (drop the type if it hits 0); move l one step right7 maxLen = the larger of maxLen and the window size (r - l + 1)8 RETURN maxLen
← / → step · space play · Home restart
Every step in words
Show all 8 steps
- Add fruits[0]=1. Basket holds {1}. 1 distinct type — within the limit of 2.
- Add fruits[1]=2. Basket holds {1,2}. Still 2 distinct types — window [0,1], maxLen=2.
- Add fruits[2]=3. Basket holds {1,2,3} — 3 distinct types! Too many for 2 baskets.
- Shrink from the left: remove fruits[0]=1 from the count. Basket is back to {2,3} — 2 types.
- Window [1,2] has length 2 — matches the current best, maxLen stays 2.
- Add fruits[3]=2. Basket holds {2,3} still — 2 types stays valid. Window [1,3], maxLen=3.
- Add fruits[4]=2. Basket still holds only {2,3} — valid! Window [1,4], length 4 beats the best: maxLen=4.
- Array exhausted. Longest run with at most 2 distinct types is [2,3,2,2] at indices 1-4. Answer: 4.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.