Given an array of integers, find the longest subarray that contains at most K distinct integers and return its length.
Example
Input: nums =[1, 2, 1, 2, 3]
, k =2
Output: 4 Explanation:the subarray nums[0...3] contains 2 distinct values: [1, 2] and is the longest subarray
Your algorithm should run in O(n^2) time and use O(n) extra space.
The problem requires finding the longest subarray within a given array of integers that contains at most K distinct integers. The output should be the length of this subarray.
nums
: An array of integers.k
: An integer representing the maximum number of distinct integers allowed in the subarray.Input: nums =[1, 2, 1, 2, 3]
, k =2
Output: 4 Explanation: The subarray nums[0...3] contains 2 distinct values: [1, 2] and is the longest subarray.
The core challenge is to find the longest contiguous subarray with at most K distinct integers. This problem is significant in scenarios where we need to analyze data streams or sequences with constraints on diversity.
Common pitfalls include not handling edge cases where K is larger than the number of unique elements in the array or when the array is empty.
To solve this problem, we can use a sliding window approach combined with a hash map to keep track of the count of distinct integers within the current window.
A naive solution would involve checking all possible subarrays and counting the distinct integers in each, which would result in an O(n^3) time complexity. This is not optimal.
We can optimize this using a sliding window approach:
Here is a step-by-step breakdown of the sliding window algorithm:
import java.util.HashMap;
import java.util.Map;
public class LongestSubarrayKDistinct {
public int lengthOfLongestSubarrayKDistinct(int[] nums, int k) {
if (nums == null || nums.length == 0 || k == 0) {
return 0;
}
// HashMap to store the count of elements in the current window
Map<Integer, Integer> map = new HashMap<>();
int left = 0, right = 0, maxLength = 0;
// Iterate through the array with the right pointer
while (right < nums.length) {
// Add the current element to the map
map.put(nums[right], map.getOrDefault(nums[right], 0) + 1);
// If the number of distinct elements exceeds k, shrink the window from the left
while (map.size() > k) {
map.put(nums[left], map.get(nums[left]) - 1);
if (map.get(nums[left]) == 0) {
map.remove(nums[left]);
}
left++;
}
// Update the maximum length of the window
maxLength = Math.max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
public static void main(String[] args) {
LongestSubarrayKDistinct solution = new LongestSubarrayKDistinct();
int[] nums = {1, 2, 1, 2, 3};
int k = 2;
System.out.println("Length of longest subarray: " + solution.lengthOfLongestSubarrayKDistinct(nums, k)); // Output: 4
}
}
The time complexity of the sliding window approach is O(n) because each element is processed at most twice (once by the right pointer and once by the left pointer). The space complexity is O(n) due to the hash map used to store the count of elements.
Consider the following edge cases:
To test the solution comprehensively, consider the following test cases:
When approaching such problems, consider the following tips:
In this blog post, we discussed how to find the longest subarray with at most K distinct integers using a sliding window approach. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for developing strong problem-solving skills in programming.
For further reading and practice, consider the following resources: