Uniform K-Subarray Sums

Moderate
0/80
2 upvotes
Asked in company
Amdocs

Problem statement

You are given an array 'arr' of N positive integers and an integer 'K'.

Your task is to find the minimum number of array elements you need to replace to make the sum of every contiguous subarray of length 'K' equal. You can replace an element with any integer.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains two space-separated integers, 'N' and 'K'.

The second line contains 'N' space-separated integers, representing the elements of the array 'arr'.


Output Format:
Print a single integer representing the minimum number of replacements required.


Note:
The condition that all K-length subarray sums are equal implies a periodic property. If the sum of {a_i, ..., a_{i+K-1}} must equal the sum of {a_{i+1}, ..., a_{i+K}}, it forces a_i to be equal to a_{i+K}. This means all elements at indices j, j+K, j+2K, ... must be the same for the sums to be equal with minimal changes.
Sample Input 1:
5 2
3 4 3 5 6


Sample Output 1:
2


Explanation for Sample 1:
To make all subarrays of length 2 have the same sum, we need `arr[i] = arr[i+2]` for all valid `i`. This creates two groups of elements that must be made equal:
  Group 0 (indices 0, 2, 4): `{3, 3, 6}`. To make them equal with minimum changes, we change them to the most frequent element, which is 3. This requires 1 change (6 -> 3).
  Group 1 (indices 1, 3): `{4, 5}`. To make them equal, we can change one to match the other. This requires 1 change (e.g., 5 -> 4).
Total minimum changes = 1 + 1 = 2.


Sample Input 2:
5 3
1 2 3 1 2


Sample Output 2:
0


Explanation for Sample 2:
The subarrays of length 3 are `{1, 2, 3}`, `{2, 3, 1}`, and `{3, 1, 2}`. All of these already have a sum of 6. No operations are needed.
Following the periodic property:
   Group 0 (indices 0, 3): `{1, 1}`. Already equal. 0 changes.
   Group 1 (indices 1, 4): `{2, 2}`. Already equal. 0 changes.
   Group 2 (index 2): `{3}`. Already equal. 0 changes.
Total changes = 0.


Expected Time Complexity:
The expected time complexity is O(N).


Constraints:
1 <= K <= N <= 10^5
1 <= arr[i] <= 10^9

Time limit: 1sec
Approaches (1)
Uniform K-Subarray Sums
Time Complexity

The expected time complexity is O(N).

Space Complexity
Code Solution
(100% EXP penalty)
Uniform K-Subarray Sums
Full screen
Console