LeetCode 228: Summary Ranges — Python Solution

LeetCode 228: Summary Ranges is an Easy intervals problem. This Python walkthrough develops a run detection solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyEasy
TopicIntervals
Reusable patternrun detection
ComplexityO(n) time and O(1) extra space excluding output

Recognizing the pattern

Sorting interval boundaries exposes a monotonic frontier: once an interval begins beyond it, earlier intervals cannot overlap again.

For this problem specifically, start a range at each unprocessed value and extend while consecutive values differ by one, then format the endpoints. The invariant worth writing beside the code is: All values before the scan index have been represented by disjoint maximal ranges.

Step-by-step algorithm

  1. Identify the input state consumed by summaryRanges(nums) and initialize the data required by the run detection pattern.
  2. Start a range at each unprocessed value and extend while consecutive values differ by one, then format the endpoints.
  3. After each update, verify the page’s central invariant: All values before the scan index have been represented by disjoint maximal ranges.
  4. Finish only after the boundary behavior is covered: Single-value runs use one number rather than an arrow.

Python solution

class Solution:
    def summaryRanges(self, nums):
        answer, i = [], 0
        while i < len(nums):
            start = nums[i]
            while i + 1 < len(nums) and nums[i + 1] == nums[i] + 1: i += 1
            end = nums[i]
            answer.append(str(start) if start == end else f"{start}->{end}")
            i += 1
        return answer

Reading the implementation

The main entry point is summaryRanges(nums). The named working state includes answer, start, end, i; those variables make the run detection state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, start a range at each unprocessed value and extend while consecutive values differ by one, then format the endpoints.

Correctness argument

Initialization. Before the scan begins, the unresolved range contains every candidate and the processed range is empty, so no answer has been lost.

Preservation. Start a range at each unprocessed value and extend while consecutive values differ by one, then format the endpoints. The chosen movement discards only candidates that cannot improve the answer; afterward, all values before the scan index have been represented by disjoint maximal ranges.

Termination. A boundary advances on every iteration. Once the active range is exhausted, every viable candidate was either measured or safely eliminated, so the stored result is optimal.

Complexity and trade-offs

O(n) time and O(1) extra space excluding output. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Checking every pair avoids sorting but does quadratic work and complicates transitive overlaps. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().summaryRanges([0,1,2,4,5,7]) == ["0->2","4->5","7"]

Common mistakes and edge cases

  • Problem-specific boundary: Single-value runs use one number rather than an arrow.
  • Pattern-level pitfall: State whether touching endpoints count as overlap and preserve the appropriate endpoint when merging.
  • Invariant check: after every update, confirm that all values before the scan index have been represented by disjoint maximal ranges.

Interview review checklist

  • Explain why run detection matches the structure of this input.
  • State the invariant in one sentence before tracing code: All values before the scan index have been represented by disjoint maximal ranges.
  • Derive O(n) time and O(1) extra space excluding output from how many times each element or state is visited.
  • Test the boundary explicitly: Single-value runs use one number rather than an arrow.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 128. Longest Consecutive Sequence · Next: 56. Merge Intervals