File: array-partition/solution.py

Date: 2026-06-06

Time: 15:16

array-partition/solution.py

Purpose

This file solves LeetCode 561 - Array Partition. Given an array of 2n integers, it forms n pairs and maximizes the sum of min(ai, bi) across all pairs. It's a greedy problem where the optimal strategy is to pair adjacent elements after sorting.

Key Components

arraypairsum(nums: list[int]) -> int — The sole function. Takes a list of 2n integers, returns the maximum possible sum of pair minimums.

The implementation is two lines:

1. nums.sort() — In-place sort, ascending. This mutates the input.

2. sum(nums[::2]) — Sum every even-indexed element (0, 2, 4, ...).

Patterns

Greedy via sorting. The insight: after sorting, pairing adjacent elements (nums[0], nums[1]), (nums[2], nums[3]), ... guarantees each min() is as large as possible. The minimum of each pair is always the left (even-indexed) element. This avoids "wasting" large values by pairing them with small ones.

Slice-based aggregation. nums[::2] uses Python's step-slice to extract every other element, which is idiomatic for this kind of structured traversal over sorted data.

Dependencies

Imports: None — pure Python, no external or standard library imports.

Imported by: array-partition/test_solution.py directly. The "Imported By" list in the prompt is misleading — those hundreds of test files don't import *this* solution; they reflect the repo's test infrastructure importing from their own respective solution.py files.

Flow

1. Sort nums in-place (O(n log n)).

2. Take every even-indexed element — these are the smaller of each adjacent pair.

3. Sum them and return.

For input [1, 4, 3, 2]: sort → [1, 2, 3, 4], pairs are (1,2) and (3,4), minimums are 1 + 3 = 4.

Invariants

Error Handling

None. Empty list returns 0 (from sum([])). Odd-length input silently produces a wrong answer rather than raising. This is fine for LeetCode's constrained input guarantees.

Topics to Explore

Beliefs