![]() |
VOOZH | about |
Given an integer array arr[]and an integer K, the task is to find the length of the longest subarray such that the frequency of each element is less than or equal to K.
Examples:
Input: arr[] = {10, 20, 30, 10, 20, 30, 10, 20}, K = 2
Output: 6
Explanation: The longest possible subarray is {10, 20, 30, 10, 20, 30} since the values 10, 20 and 30 occur at most twice in this subarray. Note that the subarrays {20, 30, 10, 20, 30, 10} and {30, 10, 20, 30, 10, 20} are also longest possible subarrays.Input: arr[] = {5, 10, 5, 10, 5, 10}, K = 1
Output: 2
Explanation: The longest possible subarray is {5, 10} since the values 5 and 10 occur at most once in this subarray. Note that the subarray [10, 5] is also longest possible subarray.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Two pointer technique. Start with two pointers l = 0 and r = 0 to mark the starting and ending of valid subarrays. Increment r to increase the length of the subarray and record the frequency of each element. If the frequency of current element becomes greater than K, then move the starting pointer l and decrement the frequency of arr[l] till the frequency of current element becomes <= K. Update the maximum length if the length of current array is greater than the maximum length.
Step-by-step algorithm:
Below is the implementation of the approach:
2
Time Complexity: O(N), where N is the size of input array arr[].
Auxiliary Space: O(N)