The Fruit Into Baskets interview question asks you to find the longest contiguous subarray that contains at most two unique numbers. The story is framed as picking fruit from trees: you have two baskets, each basket can hold only one type of fruit, and you must pick exactly one fruit from every tree continuously until you hit a third type of fruit. You want to maximize the total number of fruits picked.
This is one of the most famous Sliding Window interview pattern problems, frequently asked by Google, Amazon, and Microsoft. It is essentially the "Longest Substring with At Most 2 Distinct Characters" problem disguised with a story. It tests a candidate's ability to maintain a dynamic window and use a Hash Map to track the frequency of elements within that window.
This problem is solved using a Sliding Window with a Hash Map.
left and right.right and adding the fruit type to a Hash Map, keeping track of its frequency.left.left pointer. If its frequency becomes 0, remove it from the map.right - left + 1) whenever the map size is .Fruits: [1, 2, 1, 2, 3]
right at 0: Fruit 1. Map: {1: 1}. Max = 1.right at 1: Fruit 2. Map: {1: 1, 2: 1}. Max = 2.right at 2: Fruit 1. Map: {1: 2, 2: 1}. Max = 3.right at 3: Fruit 2. Map: {1: 2, 2: 2}. Max = 4.right at 4: Fruit 3. Map: {1: 2, 2: 2, 3: 1}. Size is 3!
left. Remove fruit 1. Map: {1: 1, 2: 2, 3: 1}. Still size 3.left. Remove fruit 2. Map: {1: 1, 2: 1, 3: 1}. Still size 3.left. Remove fruit 1. Map: {2: 1, 3: 1}. Size is 2. (Valid window is [2, 3]).
Max remains 4.delete a key from the Hash Map when its frequency drops to 0, causing the map.size() check to fail.left pointer to the last occurrence of the dropped fruit instead of moving it one by one. While possible, it's prone to bugs. The standard while loop shrink is safer and still .Memorize the template for "Longest Subarray with at most K distinct elements." The exact same code works for 2 baskets, 3 baskets, or unique characters in a string.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Sum of Distinct Subarrays With Length K | Medium | Solve | |
| Maximum Erasure Value | Medium | Solve | |
| Minimum Consecutive Cards to Pick Up | Medium | Solve | |
| Count the Number of Good Subarrays | Medium | Solve | |
| Count Complete Subarrays in an Array | Medium | Solve |