File: merge-similar-items/solution.py

Date: 2026-06-06

Time: 17:46

merge-similar-items/solution.py

Purpose

This file solves LeetCode 2363 - Merge Similar Items. It owns a single responsibility: given two lists of [value, weight] pairs (each with unique values within its own list), merge them by summing weights for matching values and return the result sorted by value. The file is self-contained — it includes both the solution and its unit tests.

Key Components

sum_weights(items1, items2) -> list[list[int]] — The sole public function. Contract:

TestSumWeights — Seven test cases covering overlapping items, no overlap, full overlap, single elements, and boundary values (max 1000).

Patterns

Accumulator via defaultdict(int) — The classic "group-and-sum" idiom. Instead of checking for key existence, defaultdict(int) initializes missing keys to 0, so weights[value] += weight works unconditionally for both lists. This collapses what would be a merge-then-aggregate into a single linear scan of each input.

Sort-at-the-end — Rather than maintaining sorted order during insertion (which would require a tree or bisect), the function dumps everything into a dict and sorts once at the end. This is O(n log n) in the total number of unique values, which dominates the O(n) insertion.

Inline tests — Tests live in the same file as the solution, runnable via python solution.py. This is the standard pattern across the entire repository.

Dependencies

Imports:

Imported by: The testsolution.py files listed in the "Imported By" section don't actually import *this* file — that list appears to be a repository-wide cross-reference artifact. The real consumer is merge-similar-items/testsolution.py, which likely imports sum_weights from this module.

Flow

1. Create an empty defaultdict(int) called weights.

2. Iterate over items1, adding each weight to weights[value].

3. Iterate over items2, doing the same — overlapping values accumulate.

4. Build a list comprehension [v, w] from weights.items().

5. sorted() orders by the first element of each sublist (value), since Python compares lists lexicographically.

6. Return the sorted result.

The entire function is three logical steps: accumulate, project, sort.

Invariants

Error Handling

None. The function trusts its inputs match the LeetCode contract. No validation of types, lengths, value ranges, or weight non-negativity. This is appropriate for a competitive programming solution where the platform guarantees valid input.

Beliefs