DSA interview question
A farm visitor walks along a row of trees, where fruits[i] is the type of fruit on tree i. They carry two baskets, each holding one type of fruit (unlimited amount). They pick one fruit from every tree, moving right from any starting tree, and must stop at the first tree whose fruit fits in neither basket. What's the most fruit they can pick? That's the longest contiguous subarray with at most two distinct values, a textbook variable-size sliding window with a count per type.
Example: [1, 2, 3, 2, 2] → 4 ([2, 3, 2, 2]).
int totalFruit(const vector<int>& fruits);
| Input | Output | Explanation |
|---|---|---|
[1, 2, 1] | 3 | Only 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] |
[1] | 1 |
(Confirm: the picked trees must be contiguous; each basket holds a single type; the answer is a count of trees.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in