PPractick

DSA interview question

Fruit Into Baskets

Medium · Algorithms · Topics: sliding window, hash map, array

The problem

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]).

Function signature

int totalFruit(const vector<int>& fruits);

Test cases

InputOutputExplanation
[1, 2, 1]3Only 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.)

How interviewers phrase it

Clarifying questions to ask

  1. Must the trees be contiguous? (Yes.)
  2. What's the range of fruit types? (That decides between an array and a hash map for counts.)
  3. Can I start anywhere? (Yes.)

Follow-ups to expect

  1. "How do you generalise to k baskets?"
  2. "Why use a count map rather than a set?"
  3. "O(1)-memory variant for two types?"
  4. "Why is it O(n)?"
  5. "Can the window shrink by more than one?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in