Given an array arr[] of size N consisting of only the first M natural numbers, the task is to find the minimum length of the subarray that is required to be replaced such that the frequency of array elements is N / M.
Note: N is a multiple of M.
Examples:
Input: M = 3, arr[] = {1, 1, 1, 1, 2, 3}
Output: 2
Explanation:
Replace the subarray over the range [2, 3] with the element {2, 3} modifies the array arr[] to {1, 1, 2, 3, 2, 3}. Now, the frequency of each array elements is N / M( = 6 / 3 = 2).
Therefore, the minimum length subarray that needed to be replaced is 2.Input: M = 6, arr[] = {1, 3, 6, 6, 2, 1, 5, 4, 1, 4, 1, 2, 3, 2, 2, 2, 4, 3}
Output: 4
Approach: The given problem can be solved by using Two Pointers Approach to find the minimum length of subarray having all the count of numbers outside this range are smaller or equal to N/M. Follow the steps below to solve the problem:
- Initialize a vector, say mapu[] of size M+1 with 0 to store the frequency of each array element.
- Initialize the variable c as 0 to store the number of elements that are additionally present in the array.
- Iterate over the range [0, N] using the variable i and performing the following tasks:
- Increase the value of arr[i] in the vector mapu[] by 1.
- If the value of mapu[arr[i]] is equal to (N/M) + 1, then increase the value of c by 1.
- If the value of c is 0, then return 0 as the result.
- Initialize the variable ans as N to store the answer and L and R two pointers as 0 and (N – 1) to store the left and right of the range.
- Iterate in a while loop till R is less than N and perform the following tasks:
- If the value of (mapu[arr[R]] – 1) is equal to N/M, then subtract the value of c by 1.
- If c is equal to 0, then Iterate in a while loop till L is less than equal to R and the value of c is equal to 0 and perform the following tasks:
- Update the value of ans as the minimum of ans or (R – L + 1)
- Increase the value of mapu[arr[L]] by 1 and if that is greater than N/M, then increase the value of c by 1.
- Increase the value of L by 1.
- Increase the value of R by 1.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach.
C++
|
Javascript
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.