Problem 561

Abstract / Summary

Given an array of even length, pair up adjacent elements and sum each pair to find the minimum total.

Note

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

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) ])
4 lines | 156 bytes | submitted September 5, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 82% (800k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Counting Sort
  • Greedy
  • Sorting
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 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.

written by openai gpt

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.

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 = 8 | μ = 7.62 | σ = 1.30

Complexity Analysis

Time: loglinear
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
generated automatically

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++ 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++
34 links | 20 authors | 10 languages

Videos

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

Similar Problems

3 similar problems

Solved On The Same Day

5 easy 6 medium
12 solutions   September 5, 2023

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