Max Sum of a Pair With Equal Sum of Digits (LeetCode 2342): Solution and Explanation

Medium
Array
Hash Table
Sorting
Heap Priority Queue

Given an array of positive integers, return the largest nums[i] + nums[j] over pairs of different indices whose numbers have the same digit sum, or -1 if no such pair exists.

Intuition

Two numbers can only pair if their digit sums match, so the array naturally splits into buckets keyed by digit sum. Pairs never cross buckets.

Inside one bucket, the largest pair sum is simply the two largest numbers in it. Every other number in the bucket is irrelevant.

That means each bucket only has to remember its current champion. When a new number arrives, pairing it with the champion gives the best pair it can be part of so far. Then the larger of the two stays as champion for later arrivals.

Approach: One pass with a champion per digit sum

  1. Create best, a map (or an array of 82 slots) from digit sum to the largest number seen with that sum, and set answer = -1.
  2. For each number x, compute its digit sum s by repeatedly adding x % 10 and dividing by 10.
  3. If bucket s already has a champion, update answer = max(answer, best[s] + x).
  4. Set best[s] = max(best[s], x).
  5. Return answer, which stays -1 if no bucket ever got a second number.

Step-by-step example

nums = [18,43,36,13,7]
  1. 18 has digit sum 9. Bucket 9 is empty, so 18 becomes its champion.
  2. 43 has digit sum 7. Bucket 7 is empty, so 43 becomes its champion.
  3. 36 has digit sum 9. It pairs with 18 for 54, so answer = 54. 36 is larger, so it becomes champion of bucket 9.
  4. 13 has digit sum 4. Bucket 4 is empty, so 13 is its champion.
  5. 7 has digit sum 7. It pairs with 43 for 50, which is less than 54. The answer is 54.

Code: Python, Java, C++

1class Solution:
2    def maximumSum(self, nums: List[int]) -> int:
3        best = {}
4        answer = -1
5        for x in nums:
6            s, y = 0, x
7            while y:
8                s += y % 10
9                y //= 10
10            if s in best:
11                answer = max(answer, best[s] + x)
12            best[s] = max(best.get(s, 0), x)
13        return answer
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log M)

Each number takes one digit loop of at most 10 steps (M is the largest value), plus constant-time bucket work.

Space

O(1)

A number up to 10^9 has digit sum at most 81, so there are at most 82 buckets no matter how long the array is.

Other approaches

Group then sort each group (time O(n log n), space O(n))

Collect every number into its digit-sum group, sort each group, and add its two largest. Correct, but sorting does extra work that only the top two values need.

Sort by (digit sum, value) (time O(n log n), space O(n))

Sort all numbers by digit sum then by value, and check adjacent last pairs of each run. Also O(n log n) and less direct than the champion map.

Brute force over all pairs (time O(n^2), space O(1))

Compare every pair's digit sums. Quadratic and far too slow for n = 10^5.

Common mistakes

  • Updating the champion before computing the pair. That pairs a number with itself when it becomes the champion.
  • Keeping the first number in each bucket instead of the largest. The champion must be replaced whenever a bigger number arrives.
  • Returning 0 instead of -1 when no pair exists.
  • Worrying about overflow unnecessarily: the largest answer is 2 * 10^9, which still fits in a signed 32-bit integer, but only just.

Frequently asked questions

Why is keeping only the largest value per bucket enough?

Any pair in a bucket sums to at most the two largest values in it. When the second-largest arrives it pairs with the largest, or the largest arrives and pairs with the current champion, which is the second-largest. Either way that best pair is seen.

How big can a digit sum get?

Numbers are at most 10^9, and the biggest digit sum below that is 999,999,999 with 81. So 82 slots cover every bucket.

Can the answer overflow a 32-bit int?

No. Two values of at most 10^9 add up to at most 2,000,000,000, which is below 2,147,483,647.