👨‍💻
Coding Interview Patterns
  • Coding Interview Patterns
  • 1. Pattern: Sliding Window
    • 1.0 Introduction
    • 1.1 Maximum Sum Subarray of Size K (easy)
    • 1.2 Smallest Subarray with a given sum (easy)
    • 1.3 Longest Substring with K Distinct Characters (medium)
    • 1.4 Fruits into Baskets (medium)
    • 1.5 No-repeat Substring (hard)
    • 1.6 Longest Substring with Same Letters after Replacement (hard)
    • 1.7 Longest Subarray with Ones after Replacement (hard)
    • 1.8 - Permutation in a String (hard)
    • 1.9 String Anagrams (hard)
    • 1.10 Smallest Window containing Substring (hard)
    • 1.11 Words Concatenation (hard)
  • 2. Pattern: Two Pointers
    • 2.0 Introduction
    • 2.1 Pair with Target Sum (easy)
    • 2.2 Remove Duplicates (easy)
    • 2.3 Squaring a Sorted Array (easy)
    • 2.4 Triplet Sum to Zero (medium)
    • 2.5 Triplet Sum Close to Target (medium)
    • 2.6 Triplets with Smaller Sum (medium)
    • 2.7 Subarrays with Product Less than a Target (medium)
    • 2.8 Dutch National Flag Problem (medium)
    • 2.9 Comparing Strings containing Backspaces (medium)
    • 2.10 Minimum Window Sort (medium)
  • 7. Pattern: Tree Breadth First Search
    • 7.0 Introduction
    • 7.1 Binary Tree Level Order Traversal (easy)
    • 7.2 Reverse Level Order Traversal (easy)
    • 7.3 Zigzag Traversal (medium)
    • 7.4 Level Averages in a Binary Tree (easy)
    • 7.5 Minimum Depth of a Binary Tree (easy)
    • 7.6 Maximum Depth of Binary Tree (easy)
    • 7.7 Level Order Successor (easy)
    • 7.8 Connect Level Order Siblings (medium)
    • 7.9 Problem Challenge 1 - Connect All Level Order Siblings (medium)
    • 7.10 Problem Challenge 2 - Right View of a Binary Tree (easy)
  • 11. Pattern: Modified Binary Search
    • 11.1 Introduction
    • 11.2 Order-agnostic Binary Search (easy)
    • 11.3
  • 16. Pattern: Topological Sort (Graph)
    • 16.1 Introduction
    • 16.2 Topological Sort (medium)
    • 16.3 Tasks Scheduling (medium)
    • 16.4 Tasks Scheduling Order (medium)
  • Contributor Covenant Code of Conduct
  • Page 1
Powered by GitBook
On this page

Was this helpful?

  1. 1. Pattern: Sliding Window

1.4 Fruits into Baskets (medium)

Problem Statement

Given an array of characters where each character represents a fruit tree, you are given two baskets and your goal is to put maximum number of fruits in each basket. The only restriction is that each basket can have only one type of fruit.

You can start with any tree, but once you have started you can’t skip a tree. You will pick one fruit from each tree until you cannot, i.e., you will stop when you have to pick from a third fruit type.

Write a function to return the maximum number of fruits in both the baskets.

Example 1:

Input: Fruit=['A', 'B', 'C', 'A', 'C']
Output: 3
Explanation: We can put 2 'C' in one basket and one 'A' in 
the other from the subarray ['C', 'A', 'C']

Example 2:

Input: Fruit=['A', 'B', 'C', 'B', 'B', 'C']
Output: 5
Explanation: We can put 3 'B' in one basket and two 'C' in 
the other basket. 
This can be done if we start with the second letter: 
['B', 'C', 'B', 'B', 'C']

Solution

This problem follows the Sliding Window pattern and is quite similar to Longest Substring with K Distinct Characters. In this problem, we need to find the length of the longest subarray with no more than two distinct characters (or fruit types!). This transforms the current problem into Longest Substring with K Distinct Characters where K=2.

Code

public int fruitsIntoBaskets(char[] arr) {
    int windowStart = 0;
    int maxFruits = 0;
    Map<Character, Integer> mp = new HashMap<>();
  
    for(int windowEnd = 0; windowEnd < arr.length; windowEnd++) {
        mp.put(arr[windowEnd], mp.getOrDefault(arr[windowEnd], 0) + 1);
        
        while(mp.size() > 2) {
            mp.put(arr[windowStart], mp.get(arr[windowStart]) - 1);
            if(mp.get(arr[windowStart]) == 0) {
                mp.remove(arr[windowStart]);
            }
            windowStart++;
        }
        maxFruits = Math.max(maxFruits, windowEnd - windowStart + 1);
    }
    return maxFruits;
}

Time Complexity

The time complexity of the above algorithm will be O(N)O(N) where ‘N’ is the number of characters in the input array. The outer for loop runs for all characters and the inner while loop processes each character only once, therefore the time complexity of the algorithm will be O(N+N)O(N+N) which is asymptotically equivalent to O(N)O(N).

Space Complexity

The algorithm runs in constant space O(1)O(1) as there can be a maximum of three types of fruits stored in the frequency map.

Similar Problems

Problem 1: Longest Substring with at most 2 distinct characters

Given a string, find the length of the longest substring in it 
with at most two distinct characters.

Solution: This problem is exactly similar to our parent problem.
Previous1.3 Longest Substring with K Distinct Characters (medium)Next1.5 No-repeat Substring (hard)

Last updated 3 years ago

Was this helpful?