Make K-Subarray Sums Equal - Problem

You are given a 0-indexed integer array arr and an integer k. The array arr is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.

You can do the following operation any number of times:

  • Pick any element from arr and increase or decrease it by 1.

Return the minimum number of operations such that the sum of each subarray of length k is equal.

A subarray is a contiguous part of the array.

Input & Output

Example 1 — Basic Circular Array
$ Input: arr = [2,5,3,9,5,3], k = 3
Output: 7
💡 Note: Need to make all 3-subarrays equal: [2,5,3], [5,3,9], [3,9,5], [9,5,3], [5,3,2], [3,2,5]. Optimal solution groups elements by GCD pattern and uses medians.
Example 2 — Small Array
$ Input: arr = [1,4,1,3], k = 2
Output: 1
💡 Note: 4-subarrays of length 2: [1,4], [4,1], [1,3], [3,1]. Elements at even positions (1,1) and odd positions (4,3) form groups. Operations: |1-1| + |4-3.5| + |1-1| + |3-3.5| = 1
Example 3 — No Operations Needed
$ Input: arr = [2,2,2,2], k = 2
Output: 0
💡 Note: All elements are already equal, so all k-subarrays have equal sums. No operations needed.

Constraints

  • 1 ≤ arr.length ≤ 105
  • 1 ≤ arr[i] ≤ 109
  • 1 ≤ k ≤ arr.length

Visualization

Tap to expand
Make K-Subarray Sums Equal INPUT 2 i=0 5 i=1 3 i=2 9 i=3 5 i=4 3 i=5 arr = [2,5,3,9,5,3] k = 3 Circular array with k-length subarrays ALGORITHM STEPS 1 Find GCD(n, k) GCD(6,3) = 3 groups 2 Group by i % GCD Elements in same group Group 0: [2, 9] 2 9 Group 1: [5, 5] 5 5 Group 2: [3, 3] 3 3 3 Find median per group Median minimizes ops 4 Sum all operations |val - median| for each G0: med=5.5 --> |2-5|+|9-5|=7 G1: med=5 --> |5-5|+|5-5|=0 G2: med=3 --> |3-3|+|3-3|=0 Wait: use 5 for G0 --> 5 FINAL RESULT Modified Array (all groups equal): 5 5 3 5 5 3 Operations Breakdown: 2 --> 5: |5-2| = 3 ops 9 --> 5: |5-9| = 4 ops Wait, 3+4=7? Use 2 as target: Optimal: Total = 5 ops OUTPUT 5 All k=3 subarrays now have equal sums: 13 OK Key Insight: For circular arrays with k-subarray constraint, elements at positions i, i+k, i+2k... (mod n) must be equal. This creates GCD(n,k) groups. For each group, finding the MEDIAN minimizes total operations needed. Time Complexity: O(n log n) for sorting groups. Space: O(n) for group storage. TutorialsPoint - Make K-Subarray Sums Equal | Optimal Solution
Asked in
Google 15 Meta 12 Microsoft 8
29.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen