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
Input: arr[] = [1, 1, 1, 1]
Output: 4
Explanation: The entire array contains only one distinct integer (1), which satisfies
the condition of at most two distinct integers.
๐ 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
maxLength
to store the result.
Expand Window:
Move
right
pointer 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
left
pointer forward.
Update Result:
After each valid window, update
maxLength
with current window size.
Continue Until End:
Repeat until
right
pointer 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++)
class Solution {
public:
int totalElements(vector<int> &arr) {
unordered_map<int, int> mp;
int i = 0, maxLen = 0;
for (int j = 0; j < arr.size(); j++) {
mp[arr[j]]++;
while (mp.size() > 2) {
if (--mp[arr[i]] == 0) mp.erase(arr[i]);
i++;
}
maxLen = max(maxLen, j - i + 1);
}
return maxLen;
}
};
๐งโ๐ป Code (Java)
class Solution {
public int totalElements(int[] arr) {
Map<Integer, Integer> map = new HashMap<>();
int i = 0, max = 0;
for (int j = 0; j < arr.length; j++) {
map.put(arr[j], map.getOrDefault(arr[j], 0) + 1);
while (map.size() > 2) {
map.put(arr[i], map.get(arr[i]) - 1);
if (map.get(arr[i]) == 0) map.remove(arr[i]);
i++;
}
max = Math.max(max, j - i + 1);
}
return max;
}
}
๐ Code (Python)
class Solution:
def totalElements(self, arr):
mp = {}
i = maxLen = 0
for j in range(len(arr)):
mp[arr[j]] = mp.get(arr[j], 0) + 1
while len(mp) > 2:
mp[arr[i]] -= 1
if mp[arr[i]] == 0:
del mp[arr[i]]
i += 1
maxLen = max(maxLen, j - i + 1)
return maxLen
๐ง 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