3 min readRishi

Summary Ranges: Collapsing Runs Into Interval Strings

"Summary Ranges" is a Easy-level staple in Google, Yandex, Microsoft loops, and it is a textbook fit for the Merge Intervals pattern — one of the nine patterns that cover the bulk of what FAANG coding interviews actually test. Part 11 of 11 in the Merge Intervals arc.

The Problem

Given a sorted array of unique integers, return the smallest sorted list of range strings covering exactly its values — "a->b" for runs, "a" for singletons. The inverse of interval merging: build intervals from points. Trivial logic, but the interviewer is watching edge handling and output hygiene.

Input:  nums = [0, 1, 2, 4, 5, 7]
Output: ["0->2", "4->5", "7"]

Recognizing the Merge Intervals Pattern

Interval problems — scheduling, calendars, resource booking — almost all reduce to one move: sort by start (or end), then sweep once while comparing each interval against a running boundary. Overlap exists when the next start is at most the current end. Sort plus linear sweep, O(n log n), is the backbone of the entire family.

Consecutive integers form a run exactly while each value is previous plus one — a single-pass run detector with a start anchor. Recognizing build-intervals as the inverse of merge-intervals files it correctly in the pattern taxonomy.

The Approach

Anchor the run start. Scan; when the next value is not current plus one, close the run — emitting the singleton or arrow form — and re-anchor. Close the final run after the loop.

Two classic slips: forgetting the trailing run, and emitting "a->a" for singletons. Walking the empty and single-element inputs before declaring done is the professional finish.

Python Solution

def summary_ranges(nums: list[int]) -> list[str]:
    """Collapse sorted unique ints into range strings."""
    result: list[str] = []
    i, n = 0, len(nums)
    while i < n:
        anchor = nums[i]
        while i + 1 < n and nums[i + 1] == nums[i] + 1:
            i += 1
        if nums[i] == anchor:
            result.append(str(anchor))
        else:
            result.append(f"{anchor}->{nums[i]}")
        i += 1
    return result

Complexity

  • Time: O(n) — each element is visited once
  • Space: O(1) — excluding the output strings

Interview Tips and Follow-Ups

  • Negative numbers work untouched — but say you checked, because "-3->-1" looks odd enough that interviewers ask.
  • Variant with duplicates allowed: skip equal neighbors inside the run loop — a one-line change worth pre-thinking.
  • The mirror question (expand range strings back to numbers) tests parsing instead — cheap to prepare as a pair.

If this clicked, continue the Merge Intervals arc in the Technical Interview category. One hundred questions, nine patterns, all in Python.

Keep reading

Newsletter

New posts, straight to your inbox

One email per post. No spam, no tracking pixels, unsubscribe anytime.

Comments

  • No comments yet. Be the first.