File: missing-ranges/solution.py

Date: 2026-06-06

Time: 18:06

Missing Ranges — missing-ranges/solution.py

Purpose

This file solves LeetCode 163: Missing Ranges. Given a sorted array of unique integers and a [lower, upper] bound, it identifies all gaps — contiguous ranges of integers not present in nums but within the bounds — and returns them as formatted strings.

Key Components

findmissingranges(nums, lower, upper) -> List[str] — The main solver. Walks the sorted array once, comparing each element against nextexpected. Whenever num > nextexpected, the gap [next_expected, num - 1] is a missing range. After the loop, any remaining gap between the last element and upper is captured.

formatrange(a, b) -> str — Formats a range as either a single number ("3") when a == b, or an arrow-delimited pair ("3->5") when a < b. This is a private helper — the underscore prefix signals it's an internal detail of this module.

Patterns

Dependencies

Imports: Only List from typing — no external or internal dependencies.

Imported by: missing-ranges/test_solution.py consumes this directly. The "Imported By" list in the prompt is misleading — those are test files across the entire repo that import from their own solution.py, not from this one.

Flow

1. Initialize result = [] and next_expected = lower.

2. For each num in the sorted input:

3. After the loop, if nextexpected <= upper, the tail [nextexpected, upper] is missing. Format and append.

4. Return result.

Time complexity: O(n). Space complexity: O(1) beyond the output list.

Invariants

Error Handling

None. The function trusts its inputs per the LeetCode contract. No exceptions are raised or caught. If nums is empty, the loop body never executes, and the post-loop check captures the entire [lower, upper] range — this is correct behavior, not an error case.

Topics to Explore

Beliefs