File: sort-array-by-increasing-frequency/solution.py

Date: 2026-06-06

Time: 19:10

sort-array-by-increasing-frequency/solution.py

Purpose

This file solves LeetCode 1636 — Sort Array by Increasing Frequency. It's one of ~400+ problem solutions in the leetcode-implementations repo, each following the same structure: a solution.py with the core algorithm, a test_solution.py for validation, and optional plan.md/review.md files.

Key Components

num_sub(nums: list[int]) -> list[int] — The sole public function. Takes an integer array and returns a new array sorted by two criteria:

1. Primary: ascending frequency (elements that appear fewer times come first)

2. Secondary: descending value (among elements with the same frequency, larger values come first)

The function name num_sub is a repo-wide convention — every solution exposes this same entry point regardless of the problem.

Patterns

The entire solution is a single sorted() call with a composite sort key: (freq[x], -x). This exploits Python's tuple comparison — it sorts by the first element, then breaks ties with the second. Negating x reverses the natural ordering for the tiebreaker, giving descending-by-value within each frequency group.

Using Counter for frequency counting + sorted with a lambda key is the idiomatic Python approach for frequency-based sorting problems. No in-place mutation — the input is untouched.

Dependencies

Imports: collections.Counter — standard library, used for O(n) frequency counting.

Imported by: The massive importedby list is misleading. Those are test files across the entire repo that share a common test harness or import pattern — they don't actually depend on this solution's logic. Only sort-array-by-increasing-frequency/testsolution.py directly tests this function.

Flow

1. Counter(nums) builds a {value: count} dictionary in a single pass — O(n).

2. sorted() produces a new list using the key (freq[x], -x) — O(n log n).

3. The sorted list is returned directly.

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

Invariants

Error Handling

None. The function trusts its caller to pass a valid list[int]. Empty lists work correctly (sorted([]) returns []). This is consistent with the repo convention — solutions mirror LeetCode's constraints and don't add defensive validation.

Topics to Explore

Beliefs