Skip to main content

Minimum Operations to Equalize Subarrays - Solution & Explanation

Practice this problem

Problem Statement

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] = [li, ri].

For each query, find the minimum number of operations required to make all elements in the subarray nums[li..ri] equal. If it is impossible, the answer for that query is -1.

Return an array ans, where ans[i] is the answer for the ith 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 [li, ri] nums[li..ri] Possibility Operations Final
nums[li..ri]
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 [li, ri] nums[li..ri] Possibility Operations Final
nums[li..ri]
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 × 104
  • 1 <= nums[i] <= 109​​​​​​​
  • 1 <= k <= 109
  • 1 <= queries.length <= 4 × 104
  • ​​​​​​​queries[i] = [li, ri]
  • 0 <= li <= ri <= n - 1

Approach Overview

Problem Overview: You are given an array and must determine the minimum number of operations required to make elements within selected subarrays equal. Each operation typically adjusts values so that all numbers in a range match a target value while minimizing total cost.

Approach 1: Brute Force with Prefix Sums (Time: O(n²), Space: O(n))

Enumerate every possible subarray using two nested loops. For each subarray, determine the value all elements should be converted to (often the maximum or median depending on the allowed operation) and compute the cost of transforming the elements. A prefix sum array helps calculate range sums quickly, so the cost of converting the subarray can be computed in constant time after scanning the range. This approach is straightforward but too slow for large inputs because the number of subarrays is O(n²).

Approach 2: Binary Search on Target Value (Time: O(n log n), Space: O(n))

Instead of testing every possible target value directly, apply binary search on the value that equalizes the subarray. For each candidate target, compute how many operations are required to transform elements using prefix sums. The key insight is that the cost function becomes monotonic when operations only increase or decrease values, which allows binary search to converge on the minimal feasible target. This reduces repeated computation across ranges and works well when the value domain is large.

Approach 3: Segment Tree with Range Queries (Time: O(n log n), Space: O(n))

Use a segment tree to support fast range queries such as maximum value or sum within a subarray. While scanning the array, query the segment tree to determine the target value that all elements should match and compute the cost using prefix sums. The segment tree allows you to update or query ranges in O(log n) time, which keeps the total complexity manageable even when evaluating many subarrays. This approach is common in advanced array optimization problems where both range aggregation and dynamic updates are required.

Recommended for interviews: Interviewers expect the optimized solution using binary search combined with efficient range queries. Starting with the brute force explanation demonstrates understanding of the cost calculation. Moving to a segment tree or binary-search-based optimization shows the ability to reduce repeated work and achieve O(n log n) performance, which is necessary for hard array problems.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force with Prefix SumsO(n²)O(n)Small arrays or when demonstrating baseline logic in interviews
Binary Search on Target ValueO(n log n)O(n)When the cost function is monotonic and you can test feasibility efficiently
Segment Tree with Range QueriesO(n log n)O(n)Large inputs requiring frequent range max or sum queries

Video Solution

Q4. Minimum Operations to Equalize Subarrays || MO's Algo || Leetcode Weekly Contest 478 || Watch2X🚀Rajan Keshari ( CSE - IIT Dhanbad )1,805 views views

Watch 1 more video solutions →

Frequently Asked Questions

Is Minimum Operations to Equalize Subarrays easy or hard?
Minimum Operations to Equalize Subarrays is classified as a Hard problem. It combines array manipulation, mathematical cost calculations, and advanced techniques such as binary search and segment trees, which require strong algorithmic intuition.
Minimum Operations to Equalize Subarrays Python/Java solution
Typical implementations compute prefix sums and optionally build a segment tree for range queries. The optimized algorithm runs in O(n log n) time and can be implemented cleanly in Python, Java, C++, or Go using iterative scans and logarithmic queries.
How to solve Minimum Operations to Equalize Subarrays in O(n)?
Pure O(n) solutions are uncommon for this problem because computing the optimal equalization target across many ranges requires ordered or aggregated queries. Most optimized implementations rely on binary search or segment tree queries, leading to O(n log n) time complexity.
What is the best approach for Minimum Operations to Equalize Subarrays?
The most practical approach combines binary search with efficient range queries such as prefix sums or a segment tree. Binary search narrows down the target value that equalizes elements, while range queries compute the cost quickly. This reduces the overall complexity to around O(n log n), which is suitable for large arrays in hard problems.
Is Minimum Operations to Equalize Subarrays asked at Google/Amazon/Meta?
Problems involving range equalization, prefix sums, and segment trees appear frequently in interviews at large tech companies such as Google, Amazon, and Meta. Variants of this question test understanding of range queries, optimization techniques, and algorithmic trade‑offs.
What data structure is used in Minimum Operations to Equalize Subarrays?
Common data structures include prefix sum arrays for fast range sum calculation and segment trees for efficient range maximum or aggregation queries. Binary search is often layered on top to find the optimal value that minimizes operations.
What is the time complexity of Minimum Operations to Equalize Subarrays?
The brute force solution that evaluates every subarray runs in O(n²) time. Optimized approaches that use binary search and range query structures such as prefix sums or segment trees typically achieve O(n log n) time with O(n) additional space.

Ready to solve this problem?

Practice Minimum Operations to Equalize Subarrays with our built-in code editor and test cases.

Practice on FleetCode