Collapse Contiguous Integer Runs

Easy · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement compress_ranges(nums: List[int]) -> str to summarize an arbitrary list of integers into a compact, comma-delimited string of non-overlapping contiguous runs.

Apply these formatting rules:

  • Increasing order: Emit runs from smallest integer value to largest, joined by "," with zero whitespace.
  • Ignore repeats: Multiple copies of the same integer behave identically to a single copy.
  • Isolated values: Any integer x without x - 1 or x + 1 in nums is formatted by itself as "x".
  • Contiguous runs of length >= 2: Every unbroken run low, low + 1, ..., high (low < high) that cannot be extended further on either side is formatted as "low-high".
  • Empty input: When nums is [], return "".

Examples

Example 1

Input: nums = [10, 6, 4, 5, 13, 7, 11]
Output: "4-7,10-11,13"

Sorting the distinct integers yields [4, 5, 6, 7, 10, 11, 13]. Values 4 through 7 collapse into "4-7", 10 and 11 collapse into "10-11", and standalone 13 stays "13".

Example 2

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

Deduplicating and ordering gives [-2, -1, 0, 4]. The negative-to-zero run -2, -1, 0 becomes "-2-0", followed by isolated "4".

Example 3

Input: nums = [12, 12, 12, 12]
Output: "12"

All four entries hold the same integer 12, leaving one isolated value "12".

Constraints

  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9

Step-by-step walkthrough

  1. Understand the goal and rules

    We receive an unsorted list of integers nums (which may be empty, contain duplicates, or include negative values) and must return a single comma-delimited string of maximal contiguous runs:

    1. Runs appear in increasing numerical order with no spaces.
    2. Repeated values are ignored ([12, 12, 12, 12] produces the same result as [12]).
    3. An isolated integer with neither x - 1 nor x + 1 present is written as "x".
    4. Any unbroken run of two or more integers low, low + 1, ..., high is collapsed into "low-high".
    Raw input:            [10, 6, 4, 5, 13, 7, 11]
    Unique & sorted:      [4, 5, 6, 7,   10, 11,   13]
    Contiguous groups:    [4 .. 7]       [10..11]  [13]
    Compressed output:    "4-7,10-11,13"
    

    Because len(nums) can reach 10^5 while element values range from -10^9 to 10^9, our runtime must depend on how many integers are given (n), never on max(nums) - min(nums).

  2. Why stepping from min to max is too slow

    A straightforward brute-force idea puts every element into a hash set and loops x through every integer from min(nums) to max(nums) + 1, opening a run when x is present and closing it when x is absent.

    While that loop is great as a tiny-input test oracle, its work scales with max(nums) - min(nums). On a two-element list [-10^9, 10^9], stepping across the gap inspects 2,000,000,001 integers for just two inputs!

    By sorting the unique integers instead, we jump directly across arbitrarily wide gaps in one step.

  3. Key idea: deduplicate, sort, and cut at gaps

    After stripping duplicates and sorting in ascending order, consecutive integers in a run sit right next to each other with a difference of +1:

    • Why deduplicate first? Sorting [2, 2, 3] without deduplicating produces a +0 step from the first 2 to the second 2, which a simple +1 check would misread as a gap and format as "2,2-3". Computing sorted(set(nums)) yields strictly increasing numbers [2, 3].
    • When does an open run close? Maintain two boundary integers for the active run: run_start (its leftmost value) and run_end (the latest value added). Whenever the next sorted value num equals run_end + 1, advance run_end = num. Otherwise num > run_end + 1, meaning a gap of at least 2 separates them—so [run_start, run_end] is complete and a new run begins at num.
    unique_sorted:  [ 4,  5,  6,  7,  |  10, 11,  |  13 ]
                      ^           ^       ^   ^      ^^
                  run_start   run_end     |   |    start & end
                     "4-7"  <-- gap (10!=8) "10-11" <-- gap (13!=12)
    
  4. Helper: format a finished run

    When [run_start, run_end] closes, an isolated value (run_start == run_end) formats without a hyphen, whereas any multi-element run (run_start < run_end) joins the two endpoints with "-".

    Negative integers need zero special handling—joining str(run_start) and str(run_end) with "-" handles negative-only runs and runs crossing zero automatically:

    [-5, -4]       -> run_start = -5, run_end = -4 -> "-5--4"
    [-2, -1, 0]    -> run_start = -2, run_end =  0 -> "-2-0"
    [12]           -> run_start = 12, run_end = 12 -> "12"
    
    def format_range(run_start: int, run_end: int) -> str:
        """Format a closed integer run [run_start, run_end] as 'a' or 'a-b'."""
        # Isolated integers have run_start == run_end, so write them without a hyphen.
        if run_start == run_end:
            return str(run_start)
        return f"{run_start}-{run_end}"
    
  5. Scan the sorted values and close the final run

    Now we put compress_ranges together:

    1. Compute unique_sorted = sorted(set(nums)). Return "" right away if unique_sorted is empty so we never index element 0 of an empty list.
    2. Seed the first open run with run_start = run_end = unique_sorted[0].
    3. Iterate num across unique_sorted[1:]. Extend run_end = num when num == run_end + 1; otherwise append format_range(run_start, run_end) and reset run_start = run_end = num.
    4. Flush after the loop: when iteration finishes, the rightmost run is still open because no gap followed it, so append format_range(run_start, run_end) once more before joining with ",".
    def compress_ranges(nums: List[int]) -> str:
        # Phase 1: Deduplicate with a set and sort ascending so consecutive integers sit side by side.
        # Why deduplicate first: a duplicate like [2, 2, 3] has step 0, which would falsely look like a gap.
        unique_sorted = sorted(set(nums))
        if not unique_sorted:
            return ""
    
        # ranges: list of formatted strings in ascending order, e.g. ["4-7", "10-11", "13"]
        ranges: List[str] = []
    
        # Track the inclusive boundaries [run_start, run_end] of the contiguous run currently open.
        run_start = unique_sorted[0]
        run_end = unique_sorted[0]
    
        # Phase 2: Scan left to right; extend the active run on +1 steps and cut whenever a gap appears.
        for num in unique_sorted[1:]:
            if num == run_end + 1:
                # Consecutive neighbor: grow the right boundary of the current run.
                run_end = num
            else:
                # Because unique_sorted is strictly increasing, num != run_end + 1 means num > run_end + 1:
                # close [run_start, run_end] and open a fresh run at num.
                ranges.append(format_range(run_start, run_end))
                run_start = num
                run_end = num
    
        # Phase 3: Flush the final run, which is still open when the loop finishes.
        ranges.append(format_range(run_start, run_end))
        return ",".join(ranges)
    
  6. Trace Example 1 step by step

    Let's walk through nums = [10, 6, 4, 5, 13, 7, 11]. First, unique_sorted becomes [4, 5, 6, 7, 10, 11, 13], with run_start = 4, run_end = 4, and ranges = []:

    num   run_end + 1   Match?   Action                                  run_start..run_end   ranges
    ---   -----------   ------   -------------------------------------   ------------------   ---------------------
    (init)                       open first run at 4                     4..4                 []
     5         5        yes      extend run_end = 5                      4..5                 []
     6         6        yes      extend run_end = 6                      4..6                 []
     7         7        yes      extend run_end = 7                      4..7                 []
    10         8        no       close 4..7 -> "4-7", reset to 10..10    10..10               ["4-7"]
    11        11        yes      extend run_end = 11                     10..11               ["4-7"]
    13        12        no       close 10..11 -> "10-11", reset 13..13   13..13               ["4-7", "10-11"]
    (after loop)                 flush final open run 13..13 -> "13"     --                   ["4-7", "10-11", "13"]
    

    Joining ranges with "," returns "4-7,10-11,13". On Example 3 ([12, 12, 12, 12]), unique_sorted is [12], the loop over unique_sorted[1:] runs zero iterations, and the post-loop flush outputs "12".

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def format_range(run_start: int, run_end: int) -> str:
        """Format a closed integer run [run_start, run_end] as 'a' or 'a-b'."""
        # Isolated integers have run_start == run_end, so write them without a hyphen.
        if run_start == run_end:
            return str(run_start)
        return f"{run_start}-{run_end}"
    
    
    def compress_ranges(nums: List[int]) -> str:
        # Phase 1: Deduplicate with a set and sort ascending so consecutive integers sit side by side.
        # Why deduplicate first: a duplicate like [2, 2, 3] has step 0, which would falsely look like a gap.
        unique_sorted = sorted(set(nums))
        if not unique_sorted:
            return ""
    
        # ranges: list of formatted strings in ascending order, e.g. ["4-7", "10-11", "13"]
        ranges: List[str] = []
    
        # Track the inclusive boundaries [run_start, run_end] of the contiguous run currently open.
        run_start = unique_sorted[0]
        run_end = unique_sorted[0]
    
        # Phase 2: Scan left to right; extend the active run on +1 steps and cut whenever a gap appears.
        for num in unique_sorted[1:]:
            if num == run_end + 1:
                # Consecutive neighbor: grow the right boundary of the current run.
                run_end = num
            else:
                # Because unique_sorted is strictly increasing, num != run_end + 1 means num > run_end + 1:
                # close [run_start, run_end] and open a fresh run at num.
                ranges.append(format_range(run_start, run_end))
                run_start = num
                run_end = num
    
        # Phase 3: Flush the final run, which is still open when the loop finishes.
        ranges.append(format_range(run_start, run_end))
        return ",".join(ranges)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine tidying up a shuffled pile of numbered packet pages to print a compact summary like "4-7,10-11,13" on a cover label. First you set aside extra copies of the same page (deduplication, keeping one copy of each distinct value), and then you place the remaining pages in ascending numerical order. Once sorted, spotting contiguous runs (unbroken chains of consecutive integers such as 4, 5, 6, 7) is straightforward: sweep from left to right, stretch the active span whenever the next page is 1 above the previous page, and record the finished span as soon as a gap of 2 or more appears.

Why does skipping the sort cause trouble? Without sorting, you might load every value into a lookup set and walk one integer at a time from min(nums) to max(nums) checking membership, or repeatedly scan the array for x + 1. Stepping from min to max scales with the numeric spread (max - min), so a two-element input [-10^9, 10^9] visits two billion integers and times out, while repeated array searches take quadratic O(n^2) time.

Here is a 5-element trace on nums = [9, 5, 5, 4, 7]:

1. Deduplicate and sort:  [9, 5, 5, 4, 7]  ->  unique_sorted = [4, 5, 7, 9]
2. Start first run at 4:  run_start = 4, run_end = 4
3. See 5 (== 4 + 1):      consecutive! Extend run_end = 5       (active run: 4..5)
4. See 7 (!= 5 + 1):      gap! Emit "4-5", start new run 7..7   (ranges: ["4-5"])
5. See 9 (!= 7 + 1):      gap! Emit "7",   start new run 9..9   (ranges: ["4-5", "7"])
6. End of list:           flush open run 9..9 -> emit "9"       (ranges: ["4-5", "7", "9"])
7. Join with commas:      "4-5,7,9"

Complexity

Let n be len(nums) and u (u <= n) be the count of unique integers.

  • Time: O(n + u log u), which is O(n log n) in the worst case when every input integer is distinct. Inserting n integers into a hash set (a hash-table collection storing unique items with O(1) average insert and lookup time) takes O(n) average time, running a comparison sort (a sorting algorithm that orders elements via pairwise comparisons in O(u log u) time) over the u unique values takes O(u log u), and sweeping unique_sorted plus joining the formatted strings visits each unique number a constant number of times in O(u).
  • Space: O(u) (at most O(n)) extra memory to store the hash set, unique_sorted, and the ranges string list.

Edge cases

  • Empty list ([]): Guard if not unique_sorted: return "" before reading unique_sorted[0] so empty input never raises IndexError.
  • Single element ([7]) or all-duplicate list ([12, 12, 12, 12]): unique_sorted has length 1, the loop over unique_sorted[1:] executes zero times, and the final flush emits "7" or "12".
  • Duplicates inside a run ([2, 2, 3, 3, 4]): Deduplicating up front produces [2, 3, 4], returning "2-4" without false splits at repeated values.
  • Two-element run ([10, 11]): Two adjacent integers already compress to "10-11".
  • Negative runs and zero-crossing runs: [-5, -4] formats as "-5--4" and [-2, -1, 0] formats as "-2-0", both handled directly by f"{run_start}-{run_end}".
  • Extreme constraint values (-10^9 and 10^9): Python integers have arbitrary precision, so run_end + 1 cannot overflow (in fixed-width 32-bit languages, adding 1 near INT_MAX requires care, though 10^9 + 1 fits in signed 32-bit).

Common mistakes

  • Sorting without deduplicating (sorted(nums) instead of sorted(set(nums))): On [2, 2, 3], the second 2 fails num == run_end + 1, tricking the loop into emitting "2,2-3".
  • Omitting the post-loop flush: Inside the loop, a run is appended only when a subsequent gap closes it, so forgetting the final ranges.append(...) drops the last run on every non-empty input.
  • Checking num == run_start + 1 instead of num == run_end + 1: Comparing against the start of the run rather than its latest element splits [4, 5, 6] into "4-5,6".
  • Joining with ", " instead of ",": Output must be "4-7,10-11,13" with zero spaces.

Alternative approaches

  • Linear run discovery in a hash set plus sorting run starts: Put nums into a set present. Any x in present where x - 1 not in present begins a maximal run; walk x + 1, x + 2, ... while in present to find its upper bound in O(u) total average time. Because runs must be emitted in ascending order, sort the k discovered (start, end) pairs in O(k log k) time (O(u log u) worst case when all values are isolated, faster when k is tiny).
  • Bitmap sweep for small bounded domains: When integers come from a narrow known range [0, R), a bitmap (a dense boolean/bit array indexed directly by integer value) avoids comparison sorting and runs in O(n + R) time.

Follow-up questions

  • Suppose integers arrive one at a time in a live feed and callers frequently ask for the current range string—what data structure would you maintain? Store the active disjoint intervals [start, end] ordered by start in a balanced binary search tree (a self-balancing search tree such as a red-black tree or sortedcontainers.SortedDict supporting O(log k) predecessor/successor lookup, insert, and delete across k intervals). When integer x arrives, locate its neighboring intervals in O(log k): ignore x if already covered, extend [a, x - 1] on the right or [x + 1, b] on the left, fuse both into [a, b] when x bridges a single-integer gap, or insert [x, x]. Formatting a query then scans the k sorted intervals in O(k) time (or if writes vastly outnumber reads, maintain hash maps end_of[start] and start_of[end] plus a seen set for O(1) average updates and O(k log k) queries).
  • What would you modify if pairs of neighbors must stay comma-separated and only runs of length three or more use a hyphen? Keep deduplication, sorting, and the gap-detection loop unchanged because the maximal contiguous runs are identical. Only adjust format_range(run_start, run_end): when run_end == run_start + 1 (a two-number run), return f"{run_start},{run_end}" instead of f"{run_start}-{run_end}".
  • How would you produce the compressed output when the unsorted integers span terabytes of disk files that exceed available RAM? Build an external merge sort pipeline (an out-of-core sort that sorts memory-sized batches to disk and streams them together). First, read RAM-sized chunks, deduplicate and sort each chunk in memory, and flush each sorted run to a temporary file. Second, open all temporary files simultaneously and merge them through a min-heap (a priority queue popping the smallest head integer across F files in O(log F) time), discarding duplicates of the previously popped integer and feeding each distinct value into our O(1)-space (run_start, run_end) state machine to stream formatted ranges straight to disk; alternatively, because values lie within [-10^9, 10^9], a single 2 * 10^9 + 1-bit bitmap (~250 MB in memory) can record every present integer in one pass over the files and emit all runs in one sequential scan.

Follow-up questions

Similar questions

More DocuSign interview questions

All 5 DocuSign questions →