#3762

Minimum Operations to Equalize Subarrays

Hard
ArrayMathBinary SearchSegment TreeHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

To equalize elements, they must share the same remainder when divided by k. We can transform the problem to finding the median of the adjusted values.

⚙️

Algorithm

3 steps
  1. 1Step 1: For each query, check if all elements have the same remainder when divided by k. If not, return -1.
  2. 2Step 2: Transform the elements by dividing by k and sort them.
  3. 3Step 3: Calculate the number of operations needed to make all elements equal to the median.
solution.py13 lines
1def min_operations(nums, k, queries):
2    results = []
3    for l, r in queries:
4        subarray = nums[l:r+1]
5        remainders = [num % k for num in subarray]
6        if len(set(remainders)) > 1:
7            results.append(-1)
8            continue
9        transformed = sorted(num // k for num in subarray)
10        median = transformed[len(transformed) // 2]
11        ops = sum(abs(num // k - median) for num in subarray)
12        results.append(ops)
13    return results

Complexity note: Sorting the subarray takes O(n log n), and checking remainders takes O(n), leading to overall efficient performance.

  • 1All elements must have the same remainder when divided by k to be equalized.
  • 2Using the median minimizes the total operations needed to equalize values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.