02. Longest Subarray with At Most Two Distinct Integers
โ GFG solution to the Longest Subarray with At Most Two Distinct Integers problem: find maximum length subarray containing at most 2 distinct elements using sliding window technique. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
You are given an array arr[] consisting of positive integers. Your task is to find the length of the longest subarray that contains at most two distinct integers.
A subarray is a contiguous sequence of elements within an array. The goal is to find the maximum possible length of such a subarray where the number of unique elements does not exceed 2.
๐ Examples
Example 1
Input: arr[] = [2, 1, 2]
Output: 3
Explanation: The entire array [2, 1, 2] contains at most two distinct integers (2 and 1).
Hence, the length of the longest subarray is 3.Example 2
Input: arr[] = [3, 1, 2, 2, 2, 2]
Output: 5
Explanation: The longest subarray containing at most two distinct integers is [1, 2, 2, 2, 2],
which has a length of 5.Example 3
๐ Constraints
$1 \le \text{arr.size()} \le 10^5$
$1 \le \text{arr}[i] \le 10^5$
โ
My Approach
The optimal approach uses the Sliding Window technique with a Hash Map to efficiently track distinct elements and their frequencies:
Sliding Window + Hash Map
Initialize Variables:
Use two pointers:
left(start of window) andright(end of window).Maintain a hash map to store frequency of elements in current window.
Track
maxLengthto store the result.
Expand Window:
Move
rightpointer and addarr[right]to the hash map.Increment its frequency.
Contract Window:
If hash map size exceeds 2 (more than 2 distinct elements), shrink window from left.
Decrement frequency of
arr[left]and remove it if frequency becomes 0.Move
leftpointer forward.
Update Result:
After each valid window, update
maxLengthwith current window size.
Continue Until End:
Repeat until
rightpointer reaches the end of array.
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. Each element is visited at most twice (once by right pointer and once by left pointer).
Expected Auxiliary Space Complexity: O(k), where k is the number of distinct elements in the current window. In the worst case, k โค 2, so effectively O(1) additional space.
๐งโ๐ป Code (C++)
๐งโ๐ป Code (Java)
๐ Code (Python)
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Let's make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated