Minimum Operations to Equalize Subarrays Problem
Description
LeetCode Problem 3762.
You are given an integer array nums and an integer k.
In one operation, you can increase or decrease any element of nums by exactly k.
You are also given a 2D integer array queries, where each queries[i] = [l_i, r_i].
For each query, find the minimum number of operations required to make all elements in the subarray nums[l_i..r_i] equal. If it is impossible, the answer for that query is -1.
Return an array ans, where ans[i] is the answer for the i^th query.
Example 1:
Input: nums = [1,4,7], k = 3, queries = [[0,1],[0,2]]
Output: [1,2]
Explanation:
One optimal set of operations:
i [l_i, r_i] nums[l_i..r_i] Possibility Operations Final nums[l_i..r_i] ans[i]
0 [0, 1] [1, 4] Yes nums[0] + k = 1 + 3 = 4 = nums[1] [4, 4] 1
1 [0, 2] [1, 4, 7] Yes nums[0] + k = 1 + 3 = 4 = nums[1] nums[2] - k = 7 - 3 = 4 = nums[1] [4, 4, 4] 2
Thus, ans = [1, 2].
Example 2:
Input: nums = [1,2,4], k = 2, queries = [[0,2],[0,0],[1,2]]
Output: [-1,0,1]
Explanation:
One optimal set of operations:
i [l_i, r_i] nums[l_i..r_i] Possibility Operations Final nums[l_i..r_i] ans[i]
0 [0, 2] [1, 2, 4] No - [1, 2, 4] -1
1 [0, 0] [1] Yes Already equal [1] 0
2 [1, 2] [2, 4] Yes nums[1] + k = 2 + 2 = 4 = nums[2] [4, 4] 1
Thus, ans = [-1, 0, 1].
Constraints:
1 <= n == nums.length <= 4 × 10^41 <= nums[i] <= 10^91 <= k <= 10^91 <= queries.length <= 4 × 10^4queries[i] = [l_i, r_i]0 <= l_i <= r_i <= n - 1
Solution
Approach: Median with a Persistent Segment Tree
Changing a number by k never changes its remainder modulo k. So a subarray can be made equal only if all its elements have the same remainder; otherwise the answer is -1. We check this in O(1) per query with a prefix count of positions where nums[i] % k differs from nums[i-1] % k.
When the remainders agree, let v[i] = nums[i] / k (integer division). Making all elements equal then means making all v[i] equal by steps of 1, and the cheapest target is the median of the subarray. The cost is the sum of |v[i] - median|.
To get the median and the sums for an arbitrary range quickly, build a persistent segment tree over the compressed values of v, where version i contains the first i elements and each node stores a count and a sum. Comparing versions r+1 and l gives the contents of v[l..r]. Descend the tree to find the (len+1)/2-th smallest value med; on the way, collect the count cl and sum sl of the values smaller than it. With total the sum of the range (from a prefix sum), the cost is
med * cl - sl + (total - sl) - med * (len - cl).
Complexity: O((n + q) log n) time and O(n log n) space.
class Solution:
def minOperations(self, nums: List[int], k: int, queries: List[List[int]]) -> List[int]:
n = len(nums)
# bad[i + 1] counts the positions j <= i whose remainder differs from nums[j - 1]
bad = [0] * (n + 1)
for i in range(n):
bad[i + 1] = bad[i] + (1 if i > 0 and nums[i] % k != nums[i - 1] % k else 0)
v = [x // k for x in nums]
vals = sorted(set(v))
m = len(vals)
rank = {x: i for i, x in enumerate(vals)}
ps = [0] * (n + 1)
for i in range(n):
ps[i + 1] = ps[i] + v[i]
# persistent segment tree over value ranks: roots[i] holds the first i elements
lc, rc, cnt, sm = [0], [0], [0], [0]
roots = [0] * (n + 1)
for i, x in enumerate(v):
pos = rank[x]
prev = roots[i]
lo, hi = 0, m - 1
cur = len(cnt)
roots[i + 1] = cur
while True:
cnt.append(cnt[prev] + 1)
sm.append(sm[prev] + x)
lc.append(lc[prev])
rc.append(rc[prev])
if lo == hi:
break
mid = (lo + hi) // 2
nxt = len(cnt)
if pos <= mid:
lc[cur] = nxt
prev = lc[prev]
hi = mid
else:
rc[cur] = nxt
prev = rc[prev]
lo = mid + 1
cur = nxt
ans = []
for l, r in queries:
if bad[r + 1] - bad[l + 1] > 0:
ans.append(-1)
continue
a, b = roots[l], roots[r + 1]
size = r - l + 1
kth = (size + 1) // 2
lo, hi = 0, m - 1
cl = sl = 0 # how many elements are smaller than the median, and their sum
while lo < hi:
mid = (lo + hi) // 2
c = cnt[lc[b]] - cnt[lc[a]]
if kth <= c:
a, b = lc[a], lc[b]
hi = mid
else:
kth -= c
cl += c
sl += sm[lc[b]] - sm[lc[a]]
a, b = rc[a], rc[b]
lo = mid + 1
med = vals[lo]
total = ps[r + 1] - ps[l]
ans.append(med * cl - sl + (total - sl) - med * (size - cl))
return ans