Skip to main content

Equal Sum Arrays With Minimum Number of Operations - Solution & Explanation

MediumArrayHash TableGreedyCounting15 min readAsked at: American Express
Practice this problem

Problem Statement

You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.

In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.

Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal.

 

Example 1:

Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].
- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].
- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].

Example 2:

Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
Output: -1
Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.

Example 3:

Input: nums1 = [6,6], nums2 = [1]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. 
- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].
- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].
- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].

 

Constraints:

  • 1 <= nums1.length, nums2.length <= 105
  • 1 <= nums1[i], nums2[i] <= 6

Approach Overview

Problem Overview: You get two integer arrays where every value is between 1 and 6. In one operation you can change any element to any value from 1 to 6. The goal is to make the sums of both arrays equal using the minimum number of operations.

Approach 1: Greedy Difference Reduction (O(n) time, O(1) space)

Start by computing the sum of both arrays. If the sums are already equal, the answer is 0. Otherwise calculate the difference diff = abs(sum1 - sum2). The key observation: each element can contribute a limited change. For example, if an element is 1, it can increase the sum by at most +5; if it is 6, it can decrease the sum by at most -5. Build a frequency count of all possible improvements from both arrays using a simple counting array.

Then greedily apply the largest possible reductions first. For example, operations that reduce the difference by 5 should be used before operations that reduce it by 4, and so on. Because values are restricted to 1..6, the maximum improvement per element is bounded, which allows you to process these gains using a constant-sized counting structure. This approach scans both arrays once and processes improvements in descending order, giving O(n) time and O(1) extra space.

This solution relies heavily on simple frequency counting and greedy selection. If you want to review these concepts, check array, greedy, and counting techniques.

Approach 2: Priority Queue for Maximum Impact Operations (O(n log n) time, O(n) space)

Another strategy explicitly tracks the best operation available at each step. Compute the current difference between the sums. For every element in both arrays, calculate the maximum change it could contribute toward reducing that difference. Push these potential improvements into a max heap.

Repeatedly pop the largest available improvement from the heap and subtract it from the remaining difference. Each pop represents one operation. Continue until the difference becomes zero or negative. The heap ensures you always apply the operation with the largest impact first.

This method is easier to reason about because the greedy choice is handled directly by the heap structure. However, maintaining the priority queue adds a log n factor and requires O(n) additional memory. It’s a good conceptual stepping stone before optimizing to the counting-based greedy solution.

Recommended for interviews: Interviewers usually expect the greedy counting solution. Recognizing that values are limited to 1..6 lets you compress all potential improvements into six buckets and solve the problem in linear time. Demonstrating the heap-based greedy idea first shows solid problem decomposition, but the optimized counting approach shows stronger algorithmic insight.

Approach 1: Greedy Difference Reduction

This approach focuses on greedy operations to reduce the sum difference between nums1 and nums2. Identify which array has the larger sum and attempt to either decrease its elements or increase the elements of the array with the smaller sum. By modifying elements towards their maximum impact (i.e., converting an element to 1 if reducing or to 6 if increasing), you can efficiently approach the sum equilibrium.

This C solution calculates the sum of both arrays. It identifies which array has a larger sum and calculates the difference. Utilizing a greedy approach, it determines the largest possible impact we can make in a single operation and keeps applying operations until the difference reduces to zero or exhaustion of possibilities.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(N + M) where N and M are the lengths of nums1 and nums2 respectively. This accounts for one pass to calculate sums and sort changes.
Space Complexity: O(1) as additional space usage is minimal.

Try this approach in the editor β†’

Approach 2: Priority Queue for Maximum Impact Operations

This approach involves using a max-heap or priority queue to always apply the most impactful operation first. By storing the difference each change can make when applied, the heap helps prioritize maximal changes to reduce operations needed. Consider this applicable when maintaining and retrieving order of largest impacts quickly is more efficient.

This C solution emulates a max-heap using a sorted array to efficiently select the largest changes. This involves computing the possible delta changes for both arrays and consuming them in the order from highest to lowest.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(N log N + M log M) due to sorting.
Space Complexity: O(N + M) for storing changes.

Try this approach in the editor β†’

Approach 3: Default Approach

Code

Python

Java

C++

Go

Try this approach in the editor β†’

Complexity Comparison

ApproachComplexity
Greedy Difference Reduction

Time Complexity: O(N + M) where N and M are the lengths of nums1 and nums2 respectively. This accounts for one pass to calculate sums and sort changes.
Space Complexity: O(1) as additional space usage is minimal.

Priority Queue for Maximum Impact Operations

Time Complexity: O(N log N + M log M) due to sorting.
Space Complexity: O(N + M) for storing changes.

Default Approachβ€”

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Greedy Difference Reduction (Counting)O(n)O(1)Optimal solution when values are limited to 1–6 and you want the fastest interview-ready approach
Priority Queue GreedyO(n log n)O(n)Useful for understanding greedy impact selection or when implementing a straightforward max-impact strategy

Video Solution

LeetCode 1775. Equal Sum Arrays With Minimum Number of Operations | Weekly Contest 230 | C++ β€’ Cherry Coding [IIT-G] β€’ 4,325 views views

Watch 9 more video solutions β†’

Frequently Asked Questions

Is Equal Sum Arrays With Minimum Number of Operations easy or hard?
The problem is classified as Medium because the brute idea is simple but the optimal solution requires recognizing the bounded value range and applying a greedy counting strategy to achieve O(n) time.
Equal Sum Arrays With Minimum Number of Operations Python/Java solution
Most implementations follow the greedy counting approach. Compute the sum difference, count potential improvements from each element, and greedily consume the largest reductions until the difference is eliminated. The same logic translates cleanly to Python, Java, C++, C#, and JavaScript.
How to solve Equal Sum Arrays With Minimum Number of Operations in O(n)?
First compute the sums of both arrays and determine the difference. For each element, calculate the maximum change it could contribute toward reducing that difference. Store counts of possible improvements (1 through 5). Greedily apply the largest improvements until the difference becomes zero or negative, which takes linear time.
What is the best approach for Equal Sum Arrays With Minimum Number of Operations?
The best approach is greedy difference reduction using counting. Calculate the sum difference between the arrays and track how much each element could change that difference (up to 5 because values range from 1 to 6). Process the largest possible reductions first using a frequency array. This runs in O(n) time and O(1) space.
Is Equal Sum Arrays With Minimum Number of Operations asked at Google/Amazon/Meta?
Greedy array optimization problems with bounded values appear frequently in interviews at companies like Amazon, Google, and Meta. This problem tests your ability to model operations as maximum improvements and apply greedy selection efficiently.
What data structure is used in Equal Sum Arrays With Minimum Number of Operations?
The optimal solution uses a counting array to track possible difference reductions. An alternative implementation uses a max heap (priority queue) to repeatedly select the operation with the largest impact.
What is the time complexity of Equal Sum Arrays With Minimum Number of Operations?
The optimal greedy counting solution runs in O(n) time where n is the total number of elements across both arrays. It uses O(1) extra space because the possible improvement values are limited to 1–5. A heap-based alternative runs in O(n log n) time due to priority queue operations.

Ready to solve this problem?

Practice Equal Sum Arrays With Minimum Number of Operations with our built-in code editor and test cases.

Practice on FleetCode