Python 0561.py
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
return sum([ nums[i] for i in range(0, len(nums), 2) ])
Difficulty
and has an acceptance rate of about 82% (800k+ submissions).
Typical patterns to solve this problem:
- Array
- Counting Sort
- Greedy
- Sorting
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method arrayPairSum. The method receives a list of integers, orders the elements in non-decreasing order, and then computes the sum of every element at an even index (0, 2, 4, …). This pattern corresponds to pairing the smallest with the next smallest, the third smallest with the fourth smallest, and so on, and accumulating the smaller value from each pair.
Key Steps
Sorting the Input
nums.sort()
The first operation rearranges the input list in place using Python’s built-in list.sort() method. This step guarantees that adjacent elements form the optimal pairs for the required sum.
Selecting Elements at Even Positions
[ nums[i] for i in range(0, len(nums), 2) ]
A list comprehension iterates over the index range starting at 0 and advancing by 2. For each index i, the element nums[i] is collected. This yields a new list containing exactly the elements that occupy even positions after sorting.
Summing the Selected Elements
return sum([ nums[i] for i in range(0, len(nums), 2) ])
The sum built-in aggregates the values produced by the comprehension, delivering the final integer result.
Edge Cases Handled
When the input list is empty, the sort call is a no-op and the range in the comprehension produces no indices. Consequently, the list comprehension yields an empty list and sum returns 0, which is the mathematically correct result for an empty collection.
If the list contains an odd number of elements, the range stops before the last index because the step size is 2. The final element, which would lack a partner, is simply ignored. This behavior aligns with the definition of pairing the list into floor(n/2) pairs and summing the smaller member of each pair.
The algorithm works uniformly for negative numbers, zeros, and large positive integers. Sorting places negative values at the beginning, ensuring they are paired correctly, and the subsequent summation respects their sign.
Duplicate values pose no difficulty; identical numbers are adjacent after sorting, and the comprehension picks the first of each duplicate pair, which is consistent with the intended pairing strategy.
Performance Optimizations
The use of the in-place sort method leverages Python’s highly tuned Timsort algorithm, which adapts to existing order in the data and minimizes movement of elements. By sorting directly on the original list, the implementation avoids allocating additional storage for a sorted copy.
The list comprehension combined with sum processes the elements in a single pass after sorting. Although a generator expression could avoid constructing an intermediate list, the current approach still benefits from Python’s internal optimizations for list comprehensions, which are executed in C speed and thus incur minimal overhead.
Overall, the method achieves the desired result with a concise sequence of built-in operations that are each optimized for typical workloads.
ELI5 - Simplified Explanation
Imagine a group of friends who want to play a game where they form pairs. Each friend has a number written on their shirt. To play, every pair picks the smallest number written on their shirts. To get the biggest total score possible from all these small numbers, the friends first line up by sorting themselves from the smallest number to the largest number. Once they are in a long line, the first two friends become a pair, then the next two friends become a pair, and this continues all the way to the end. Since the friends are standing in order, the person on the left side of each pair is always the one with the smaller number. The code walks down the line, picking that person from every pair, and adds those numbers together to find the final score.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
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++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Go | Rust | JS | Java | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| chandansgowda | Python | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| chandansgowda | Python | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 1984: Minimum Difference Between Highest and Lowest of K Scores
- problem 2144: Minimum Cost of Buying Candies With Discount
- problem 2155: All Divisions With the Highest Score of a Binary Array
Solved On The Same Day
- problem 168: Excel Sheet Column Title
- problem 171: Excel Sheet Column Number
- problem 506: Relative Ranks
- problem 628: Maximum Product of Three Numbers
- problem 908: Smallest Range I
- problem 306: Additive Number
- problem 307: Range Sum Query - Mutable
- problem 378: Kth Smallest Element in a Sorted Matrix
- problem 692: Top K Frequent Words
- problem 720: Longest Word in Dictionary
- problem 910: Smallest Range II
Extra
- 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