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
xwithoutx - 1orx + 1innumsis formatted by itself as"x". - Contiguous runs of length
>= 2: Every unbroken runlow, low + 1, ..., high(low < high) that cannot be extended further on either side is formatted as"low-high". - Empty input: When
numsis[], 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
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:- Runs appear in increasing numerical order with no spaces.
- Repeated values are ignored (
[12, 12, 12, 12]produces the same result as[12]). - An isolated integer with neither
x - 1norx + 1present is written as"x". - Any unbroken run of two or more integers
low, low + 1, ..., highis 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 reach10^5while element values range from-10^9to10^9, our runtime must depend on how many integers are given (n), never onmax(nums) - min(nums).Why stepping from min to max is too slow
A straightforward brute-force idea puts every element into a hash set and loops
xthrough every integer frommin(nums)tomax(nums) + 1, opening a run whenxis present and closing it whenxis 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 inspects2,000,000,001integers for just two inputs!By sorting the unique integers instead, we jump directly across arbitrarily wide gaps in one step.
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+0step from the first2to the second2, which a simple+1check would misread as a gap and format as"2,2-3". Computingsorted(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) andrun_end(the latest value added). Whenever the next sorted valuenumequalsrun_end + 1, advancerun_end = num. Otherwisenum > run_end + 1, meaning a gap of at least2separates them—so[run_start, run_end]is complete and a new run begins atnum.
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)- Why deduplicate first? Sorting
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)andstr(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}"Scan the sorted values and close the final run
Now we put
compress_rangestogether:- Compute
unique_sorted = sorted(set(nums)). Return""right away ifunique_sortedis empty so we never index element0of an empty list. - Seed the first open run with
run_start = run_end = unique_sorted[0]. - Iterate
numacrossunique_sorted[1:]. Extendrun_end = numwhennum == run_end + 1; otherwise appendformat_range(run_start, run_end)and resetrun_start = run_end = num. - 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)- Compute
Trace Example 1 step by step
Let's walk through
nums = [10, 6, 4, 5, 13, 7, 11]. First,unique_sortedbecomes[4, 5, 6, 7, 10, 11, 13], withrun_start = 4,run_end = 4, andranges = []: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
rangeswith","returns"4-7,10-11,13". On Example 3 ([12, 12, 12, 12]),unique_sortedis[12], the loop overunique_sorted[1:]runs zero iterations, and the post-loop flush outputs"12".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 isO(n log n)in the worst case when every input integer is distinct. Insertingnintegers into a hash set (a hash-table collection storing unique items withO(1)average insert and lookup time) takesO(n)average time, running a comparison sort (a sorting algorithm that orders elements via pairwise comparisons inO(u log u)time) over theuunique values takesO(u log u), and sweepingunique_sortedplus joining the formatted strings visits each unique number a constant number of times inO(u). - Space:
O(u)(at mostO(n)) extra memory to store the hash set,unique_sorted, and therangesstring list.
Edge cases
- Empty list (
[]): Guardif not unique_sorted: return ""before readingunique_sorted[0]so empty input never raisesIndexError. - Single element (
[7]) or all-duplicate list ([12, 12, 12, 12]):unique_sortedhas length1, the loop overunique_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 byf"{run_start}-{run_end}". - Extreme constraint values (
-10^9and10^9): Python integers have arbitrary precision, sorun_end + 1cannot overflow (in fixed-width 32-bit languages, adding1nearINT_MAXrequires care, though10^9 + 1fits in signed 32-bit).
Common mistakes
- Sorting without deduplicating (
sorted(nums)instead ofsorted(set(nums))): On[2, 2, 3], the second2failsnum == 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 + 1instead ofnum == 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
numsinto a setpresent. Anyxinpresentwherex - 1 not in presentbegins a maximal run; walkx + 1, x + 2, ...while inpresentto find its upper bound inO(u)total average time. Because runs must be emitted in ascending order, sort thekdiscovered(start, end)pairs inO(k log k)time (O(u log u)worst case when all values are isolated, faster whenkis 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 inO(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 bystartin a balanced binary search tree (a self-balancing search tree such as a red-black tree orsortedcontainers.SortedDictsupportingO(log k)predecessor/successor lookup, insert, and delete acrosskintervals). When integerxarrives, locate its neighboring intervals inO(log k): ignorexif already covered, extend[a, x - 1]on the right or[x + 1, b]on the left, fuse both into[a, b]whenxbridges a single-integer gap, or insert[x, x]. Formatting a query then scans theksorted intervals inO(k)time (or if writes vastly outnumber reads, maintain hash mapsend_of[start]andstart_of[end]plus aseenset forO(1)average updates andO(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): whenrun_end == run_start + 1(a two-number run), returnf"{run_start},{run_end}"instead off"{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
Ffiles inO(log F)time), discarding duplicates of the previously popped integer and feeding each distinct value into ourO(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 single2 * 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
- 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?
- What would you modify if pairs of neighbors must stay comma-separated and only runs of length three or more use a hyphen?
- How would you produce the compressed output when the unsorted integers span terabytes of disk files that exceed available RAM?
Similar questions
- Remove Consecutive Anagram Words
- Maximum Connected Land Sum and Coordinates
- Key-Value CRUD Store
- Recursive JSON Payload Schema Validator
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
More DocuSign interview questions
- Recursive JSON Payload Schema Validator Easy
- Maximum Connected Land Sum and Coordinates Medium
- Remove Consecutive Anagram Words Medium Pro
- Key-Value CRUD Store Medium Pro