Problem 1775

Abstract / Summary

Make two arrays have equal sums by moving numbers between them using the fewest moves possible.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1775.py

class Solution:
    def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
        have = sum(nums1)
        need = sum(nums2)
        if have == need:
            return 0

        # ensure have <= need
        if have > need:
            have,  need  = need,  have
            nums1, nums2 = nums2, nums1

        # make small numbers bigger,  compute the maximum change (convert from any digit to 6)
        more = [ 6 - n for n in nums1 if n != 6 ] # small optimization: skip 6s
        # make large numbers smaller, compute the maximum change (convert from any digit to 1)
        less = [ n - 1 for n in nums2 if n != 1 ]

        # each change reduces the difference between "have" and "need"
        diff    = need - have
        changes = more + less
        for steps, fix in enumerate(sorted(changes, reverse = True)): # largest changes first
            diff -= fix
            if diff <= 0:
                return steps + 1 # 1-based

        return -1
26 lines | 1005 bytes | submitted July 23, 2024 | GitHub   38% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (60k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Counting
  • Greedy
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution.minOperations method computes the minimum number of digit-change operations required to make the sum of two integer arrays equal. Each operation may replace a digit in either array with any value from 1 to 6, and the algorithm always chooses the change that yields the largest possible reduction of the current sum difference. The implementation first normalizes the problem so that the first array never has a larger sum than the second, then builds two lists of potential gains, sorts them in descending order, and applies the biggest gains until the sums match or it becomes impossible.

Normalizing the direction of the problem

have = sum(nums1)
need = sum(nums2)
if have == need:
    return 0

if have > need:
    have, need = need, have
    nums1, nums2 = nums2, nums1

The code begins by calculating the sums of the two input lists. When the sums are already equal, it returns immediately with zero operations. If the first sum exceeds the second, the variables and the corresponding lists are swapped. This guarantees that subsequent logic always works with have being the smaller sum and need the larger one, simplifying the handling of the difference.

Building the list of maximal possible changes

more = [6 - n for n in nums1 if n != 6]
less = [n - 1 for n in nums2 if n != 1]

Two list comprehensions generate the potential contribution of each element to reducing the gap. For the array with the smaller sum (nums1), the best improvement is turning any digit into a 6, so the gain is 6 - n. Digits already equal to 6 cannot contribute further and are omitted, which avoids unnecessary zero entries.

For the array with the larger sum (nums2), the optimal reduction is turning any digit into a 1, giving a gain of n - 1. Digits already equal to 1 are excluded for the same reason. This selective construction reduces the size of the combined list and eliminates trivial operations.

Combining and ordering the possible gains

diff = need - have
changes = more + less
for steps, fix in enumerate(sorted(changes, reverse=True)):
    diff -= fix
    if diff <= 0:
        return steps + 1

The current difference between the sums is stored in diff. The two gain lists are concatenated into a single collection changes. The algorithm sorts this collection in descending order, ensuring that the largest possible reduction is applied first. The loop iterates over the sorted gains, subtracting each from diff. As soon as diff becomes non-positive, the required number of operations has been reached, and the function returns the count (converted to 1-based indexing by adding one to the zero-based steps).

Handling the impossible case

return -1

If the loop exhausts all possible gains without reducing diff to zero or below, the function reaches the final return statement. This indicates that even after converting every eligible digit to its extreme value (6 for the smaller-sum array, 1 for the larger-sum array), the sums cannot be equalized. The return value -1 signals that no sequence of allowed operations can achieve the goal.

Edge conditions addressed by the implementation

The early equality check (have == need) covers the scenario where no work is required. The swap block ensures that the algorithm does not need separate logic for the case where the first array’s sum is larger; it treats both situations uniformly after the swap. By filtering out digits already at their extreme values (6 in nums1 and 1 in nums2), the code avoids processing operations that would have zero effect, which also prevents an infinite loop in pathological inputs. The final -1 return gracefully handles inputs where the total achievable gain is insufficient, such as when both arrays consist solely of digits that cannot be altered to bridge the remaining gap.

Performance considerations

The use of list comprehensions for more and less creates the gain lists in a single pass over each input array, minimizing overhead. Skipping digits that are already at their optimal values reduces the number of elements that must be sorted, which can be significant when the arrays are large and contain many 6s or 1s. Sorting is performed only once on the combined list of gains, and the subsequent linear scan stops as soon as the required reduction is achieved, avoiding unnecessary iterations. The early return on equality and the immediate exit once diff reaches zero further cut down on work for favorable inputs.

written by openai gpt

ELI5 - Simplified Explanation

Imagine two rows of toy blocks where each block has a number on it. Some blocks have small numbers like one, and some have big numbers like six. Each row adds up to a total score. The goal is to make the total score of both rows the same by picking one block and swapping its number for something else.

First, the code calculates the starting score for each row. If the scores are already the same, no work is needed. If they are different, the code checks which row needs a bigger score and which one needs a smaller score to balance them out.

To make the scores match as quickly as possible, it looks at how much each block can change. A block with a one in the row that needs more points can jump all the way up to a six, which is a big change. A block with a six in the row that needs fewer points can drop all the way down to a one, which is also a big change.

The code collects all these possible changes into a big pile and sorts them from the biggest change to the smallest one. Then, it starts picking the biggest changes one by one. Each time a change happens, the gap between the two rows gets smaller. The code keeps track of how many changes it makes until the two rows finally have the same total score. If the gap is still too big even after using every possible change, it knows it is impossible to make them match.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.35 | σ = 1.11

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Go
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
wisdompeak C++
22 links | 13 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

4 solutions   July 23, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality