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
Key Insight: Since the array is circular, elements at positions that differ by
Example: If
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
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
โก Linearithmic
Space Complexity
O(n)
Space to store cycles and sorted values
โก Linearithmic Space
Constraints
- 1 โค arr.length โค 105
- 1 โค arr[i] โค 109
- 1 โค k โค arr.length
- Array is guaranteed to be circular
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code