LeetCode 228: Summary Ranges — Python Solution

Solve LeetCode 228: Summary Ranges in Python with a run detection approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

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

What the problem is testing

Start a range at each unprocessed value and extend while consecutive values differ by one, then format the endpoints.

Algorithm

  1. Start a range at each unprocessed value and extend while consecutive values differ by one, then format the endpoints.
  2. Maintain this invariant: All values before the scan index have been represented by disjoint maximal ranges.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

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

Why this is correct

The proof follows the maintained state: All values before the scan index have been represented by disjoint maximal ranges. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

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

Edge cases

Single-value runs use one number rather than an arrow.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


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