Fruit Into Baskets solution explained
Fruit Into Baskets is a story about picking fruit with two baskets that each hold one kind, and it reduces to a plain question: what is the longest stretch of a list that contains at most two distinct values? Answer it with a sliding window that counts each value inside it, moving the left edge forward whenever a third value appears. That is O(n) time, and a variant that remembers only the last two types and the length of the final same-type run needs O(1) extra memory.
By Evin JohnPublished 8 min read
The orchard rules
A row of trees stands in a line, and each tree bears one type of fruit, given as an integer. You carry two baskets. Each basket accepts only one type, but it can hold as much of that type as you like. You choose any tree to start at, then move right one tree at a time, picking exactly one fruit from each tree you pass. The moment you reach a tree whose fruit fits neither basket, you stop. How many fruits can you collect at most?
[3, 3, 1, 3, 2, 2, 1] -> 4 start at the first tree: 3 3 1 3
[7, 8, 7, 9, 9, 8, 8, 9] -> 5 start at the first 9: 9 9 8 8 9
[1, 2, 3, 4] -> 2 any two neighbors
[4, 4, 4] -> 3 one basket is enoughTranslate the story first
Most of the difficulty is the wording. Strip it away: you collect a contiguous block of trees, because you walk without skipping, and the block can contain at most two fruit types, because you have two baskets. So the answer is the length of the longest contiguous subarray with at most two distinct values. Saying that sentence out loud early is worth a lot in an interview, since it shows you can turn a story into a known pattern, and every approach below works on that plain version.
Check two details with the interviewer: you may start anywhere (yes), and once you stop you cannot continue past the blocking tree (also yes). If either were different, for example if you could skip trees, this would become a counting question rather than a window question.
Trying every starting tree
For each start, walk right while keeping a set of types seen; stop when a third type would enter, and record how far you got. There are n starts and each walk can be up to n trees long, so this is O(n²). It is still the right thing to mention first, and it makes an easy reference for random tests.
def total_fruit_slow(trees):
best = 0
for start in range(len(trees)):
kinds = set()
for end in range(start, len(trees)):
kinds.add(trees[end])
if len(kinds) > 2:
break
best = max(best, end - start + 1)
return bestLook at what the walks repeat. When the walk from one start is blocked by a third type, the walk from the next start rereads most of the same trees. A sliding window keeps the trees between two pointers and only ever moves each pointer forward.
The window with type counts
Keep a left pointer and a dictionary from fruit type to how many trees of that type are inside the window. Move the right pointer one tree at a time and add its type. If the dictionary now has three keys, the window is invalid, so move the left pointer forward, decreasing counts and deleting a type when its count reaches zero, until only two types remain. After that, the window is valid and its length is a candidate answer. Both pointers only move right, so the total work is linear.
from collections import defaultdict
def total_fruit(trees):
count = defaultdict(int)
left = best = 0
for right, kind in enumerate(trees):
count[kind] += 1
while len(count) > 2: # a third type entered: shrink
gone = trees[left]
count[gone] -= 1
if count[gone] == 0:
del count[gone]
left += 1
best = max(best, right - left + 1)
return bestDeleting a key whose count drops to zero is not optional. The loop condition checks the number of keys, so a leftover key with a count of zero would make the window look like it still has three types, and the left pointer would run too far.
A constant-memory version
Because the limit is exactly two, you can skip the dictionary. Remember the type of the latest tree, the other type in the current run, and how many trees at the end of the run share the latest type. When a tree matches either remembered type, the run grows by one. When it is a new type, the new run is the trailing block of the latest type plus this tree, because that block is the only part of the old run that can sit next to the new type.
function totalFruit(trees) {
let best = 0;
let run = 0; // length of the current valid stretch
let other = null; // the older of the two types in the stretch
let last = null; // the type of the most recent tree
let tail = 0; // trees at the end of the stretch that are of type last
for (const kind of trees) {
run = kind === last || kind === other ? run + 1 : tail + 1;
if (kind === last) {
tail++;
} else {
tail = 1;
other = last;
last = kind;
}
best = Math.max(best, run);
}
return best;
}Trace [7, 8, 7, 9, 9, 8, 8, 9]. After 7, 8, 7 the run is 3 with a tail of one 7. The 9 is new, so the run restarts as that tail plus the 9, giving 2, and the second 9 makes it 3. The 8 is new again (the remembered types are now 7 and 9), so the run restarts as the two trailing 9s plus the 8, giving 3. The next 8 and the final 9 both match, and the run climbs to 5. Using null for the empty starting state avoids clashing with any real fruit type.
More than two baskets
A common follow-up raises the basket count to k. The dictionary version handles that by changing the 2 in the loop condition to k; the constant-memory version does not generalize. The same skeleton also answers the string question about the longest substring with at most k distinct characters. Either way, the dictionary holds at most k + 1 keys at a time.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Walk from every start | O(n²) | O(1): the set never holds more than three types |
| Window with type counts | O(n) | O(1) for two baskets, O(k) for k baskets |
| Last two types plus trailing run | O(n) | O(1) |
Rows worth testing
- An empty row: 0.
- A single tree: 1.
- Only one type in the whole row: the full length.
- Every tree a different type: 2, unless the row has fewer than two trees.
- Alternating pairs that switch types, such as 1, 2, 1, 3, 1, 3: the window has to jump forward correctly.
What goes wrong
- Answering the story literally and simulating basket swaps, which is slow and easy to get wrong.
- Leaving zero-count keys in the dictionary, so the window shrinks too far.
- Moving the left pointer by only one step with an if instead of a while.
- In the constant-memory version, restarting the run at 1 or 2 instead of the trailing block plus one.
- Treating the two most frequent types overall as the answer, which ignores contiguity.
How it might sound in the room
Fictional example
- Candidate
- I collect a contiguous block of trees, and the block can contain at most two types. So I want the longest subarray with at most two distinct values.
- Candidate
- Trying every start is n squared. Instead I will slide a window and count each type inside it.
- Candidate
- When a third type enters, I move the left edge forward and drop types whose count hits zero, until only two remain. Then I record the window length.
- Interviewer
- What if I gave you five baskets?
- Candidate
- Only the limit in the while condition changes. The dictionary then holds at most six types at once.
Related problems
Max Consecutive Ones III uses the same grow-and-shrink window, with a budget of zeros instead of a limit on types. Longest Substring Without Repeating Characters shrinks the window on a repeat instead of on a new type. Sliding Window Median keeps the window size fixed and asks about its order instead. For a counting problem with no window at all, see Longest Palindrome.
Practicing it with Natively
The step that earns credit here is the translation from orchard to subarray, so practice saying it before you code. Natively, on Mac and Windows, can read a story problem like this from a screenshot during a mock session, suggest the reframing and the window, and transcribe your answer so you can see whether you named the pattern early or only after writing code. The AI assistant for coding interviews page has more detail.
Questions people ask
How do you solve Fruit Into Baskets?
Treat it as the longest contiguous subarray with at most two distinct values. Slide a window, count each type inside it, and move the left edge forward while a third type is present. The best window length is the answer.
What is the time complexity of Fruit Into Baskets?
O(n) with a sliding window, because each pointer only moves forward. Trying every starting tree is O(n squared).
Can Fruit Into Baskets be solved without a hash map?
Yes. Track the last two fruit types and how many trees at the end of the current run share the latest type. A new type restarts the run at that trailing count plus one, using O(1) memory.
What if there are k baskets instead of two?
Use the window with a count per type and shrink while more than k types are inside. It is the same problem as the longest substring with at most k distinct characters.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
