Make K-Subarray Sums Equal - Problem
Circular Array Balancing Challenge

Imagine you have a circular integer array where elements are connected in a loop - the first element follows the last, and vice versa. Your mission is to make all consecutive subarrays of length k have the same sum using the minimum number of operations.

In each operation, you can increase or decrease any element by 1. The question is: what's the minimum total cost to achieve perfect balance?

Key Insight: Since the array is circular, elements at positions that differ by k must have the same value in the final state!

Example: If arr = [1,4,1,3] and k = 2, subarrays are [1,4], [4,1], [1,3], [3,1]. For all sums to be equal, we need 1+4 = 4+1 = 1+3 = 3+1, which means opposite elements must be equal.

Input & Output

example_1.py โ€” Basic Case
$ Input: arr = [1,4,1,3], k = 2
โ€บ Output: 1
๐Ÿ’ก Note: Subarrays are [1,4], [4,1], [1,3], [3,1] with sums 5,5,4,4. We can change arr[2] from 1 to 2, making all sums equal to 5. Total operations: 1.
example_2.py โ€” All Equal
$ Input: arr = [2,5,5,7], k = 3
โ€บ Output: 5
๐Ÿ’ก Note: Subarrays are [2,5,5], [5,5,7], [5,7,2], [7,2,5] with sums 12,17,14,14. Using GCD(4,3)=1, all positions form one cycle. Median is 5, so we need |2-5|+|5-5|+|5-5|+|7-5|=5 operations.
example_3.py โ€” Edge Case k=1
$ Input: arr = [1,2,3,4], k = 1
โ€บ Output: 0
๐Ÿ’ก Note: When k=1, each subarray has length 1, so each element forms its own sum. No operations needed since each sum is already 'equal' to itself.

Visualization

Tap to expand
Circular Array Cycle Visualizationarr[0]=1arr[1]=4arr[2]=1arr[3]=3k=2 stepsSubarray [1,4] sum=5Subarray [4,1] sum=5Subarray [1,3] sum=4Subarray [3,1] sum=4Need to balance!Solution: Change arr[2] from 1 to 2, making all sums equal to 5Operations needed: |1-2| = 1
Understanding the Visualization
1
Identify Constraint
All subarrays of length k must have equal sums
2
Find Cycles
Positions i and (i+k)%n must be equal in optimal solution
3
Apply Median Rule
For each cycle, median value minimizes total operations
Key Takeaway
๐ŸŽฏ Key Insight: In a circular array, positions that are k steps apart must have equal values for all k-subarrays to have equal sums. Use GCD to find cycles and median to minimize operations.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n log n)

O(n) to group into cycles, O(n log n) for sorting values in cycles

n
2n
โšก Linearithmic
Space Complexity
O(n)

Space to store cycles and sorted values

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค arr.length โ‰ค 105
  • 1 โ‰ค arr[i] โ‰ค 109
  • 1 โ‰ค k โ‰ค arr.length
  • Array is guaranteed to be circular
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 24
32.0K Views
Medium Frequency
~25 min Avg. Time
950 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