Array Partition (LeetCode 561): Solution and Explanation

Easy
Array
Greedy
Sorting
Counting Sort

Split an array of 2n integers into n pairs so that the sum of each pair's minimum is as large as possible, and return that sum.

Intuition

Each pair scores only its smaller number. The larger one is thrown away, so the goal is to throw away as little as possible.

Look at the largest value. It is never the minimum of any pair, so it is lost whatever you do. The cheapest partner for it is the second largest value, because then the second largest is the one that gets counted.

Remove those two and repeat on the rest. You end up pairing neighbours in sorted order: the two largest, the next two, and so on.

After sorting, every pair is (nums[2k], nums[2k+1]) and its minimum is nums[2k]. The answer is the sum of the even-index elements.

Approach: Sort and sum the even indices

  1. Sort nums in ascending order.
  2. Set total = 0.
  3. Walk i = 0, 2, 4, ... and add nums[i], the smaller member of the pair (nums[i], nums[i+1]).
  4. Return total.

Step-by-step example

nums = [1,4,3,2]
  1. Sort the array: [1,2,3,4].
  2. Pair (1,2) scores 1, total = 1. The 2 is given up.
  3. Pair (3,4) scores 3, total = 4. The 4 is given up.
  4. All pairs are scored, so return 4.

Code: Python, Java, C++

1class Solution:
2    def arrayPairSum(self, nums: List[int]) -> int:
3        nums.sort()
4        total = 0
5        for i in range(0, len(nums), 2):
6            total += nums[i]
7        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting dominates. The pairing pass is a single linear walk.

Space

O(1)

The sort is done in place apart from the language's sort overhead, and only a running total is kept.

Other approaches

Counting sort over the value range (time O(n + R) with R = 20001, space O(R))

Values lie in [-10^4, 10^4], so count each value in an array of 20001 buckets. Walk the buckets in order with a flag that alternates between take and skip, adding the value on every take.

Try every pairing (time O((2n-1)!!), space O(n))

Enumerate all ways to split the array into pairs and keep the best sum. Correct but the number of pairings grows like (2n-1)!!, so it is only useful for checking small cases.

Common mistakes

  • Adding the odd-index elements. After an ascending sort those are the larger numbers in each pair, which the problem never counts.
  • Sorting JavaScript numbers with the default sort. It compares as strings, so -10 lands after -2. Pass a numeric comparator.
  • Assuming values are non-negative. Negative numbers are allowed, and the same rule still holds: the answer itself can be negative.

Frequently asked questions

Why is pairing neighbours in sorted order optimal?

The largest value is never counted. Pairing it with the second largest means the second largest is counted, and no other choice can count a bigger number from that pair. Applying the same argument to the remaining numbers gives the sorted neighbour pairing.

Can this be solved in linear time?

Yes. The value range is small and fixed, so counting sort orders the values in O(n + 20001). Then take every other value as you walk the counts.

Does the pairing have to be unique?

No. Only the sum is returned, so any pairing with the same minimums is fine. Sorted neighbours is just the easiest one to build.