File: maximum-number-of-pairs-in-array/solution.py

Date: 2026-06-06

Time: 17:39

maximum-number-of-pairs-in-array/solution.py

Purpose

This file solves LeetCode 2341 — Maximum Number of Pairs in Array. Given an array of integers, it counts how many pairs of equal values can be formed and how many elements are left over. It exports a single function that serves as the solution entry point.

Key Components

countpairsleftovers(nums: list[int]) -> list[int] — The sole function. Takes a list of integers, returns a two-element list [pairs, leftovers] where pairs is the total number of matching pairs and leftovers is the count of unmatched elements.

The contract: every element in nums is accounted for exactly once — either as part of a pair or as a leftover. This means pairs * 2 + leftovers == len(nums) always holds.

Patterns

Frequency counting via Counter — Rather than simulating the pair-removal process described in the problem (repeatedly find two equal elements and remove them), the solution jumps straight to the closed-form answer: for any value appearing c times, it contributes c // 2 pairs and c % 2 leftovers. This is the standard idiom for "count pairs" problems — avoid simulation, count frequencies, do integer division.

Accumulator loop — The function accumulates pairs and leftovers independently across all frequency values. No intermediate data structures beyond the Counter.

Dependencies

Imports: collections.Counter — the only dependency. No custom data structures or helpers.

Imported by: The corresponding maximum-number-of-pairs-in-array/test_solution.py. The large "Imported By" list in the provided context is an artifact of the repo's test infrastructure — those test files import a shared test runner or utility, not this solution directly.

Flow

1. Counter(nums) builds a frequency map in O(n).

2. The loop iterates over each unique value's count — O(k) where k is the number of distinct values.

3. Integer division (// 2) extracts pairs; modulo (% 2) extracts leftovers.

4. Returns the accumulated [pairs, leftovers].

Total: O(n) time, O(k) space.

Invariants

Error Handling

None. The function trusts its input — no validation of types, empty lists, or negative values. An empty nums returns [0, 0] naturally since Counter({}).values() is empty and the accumulators start at zero.