Summarize Integer Ranges into String
Greedy & IntervalsAuto-graded · 26 test casesLast updated
Process an unorganized array of integers by sorting, deduplicating, and formatting contiguous numerical ranges into a compact string.
Given an unsorted list of integers nums, produce a single string representing the numbers as contiguous ranges formatted in ascending order.
Requirements
- Ignore duplicate integer values.
- The formatted ranges must appear in strictly ascending numerical order.
- If an integer is isolated (no immediately preceding or succeeding integer in the input set), represent it as a single integer string (e.g.,
"7"). - If two or more adjacent integers form a continuous sequence
[x, x+1, ..., y], represent the sequence as"x-y". - Join all resulting formatted segments with commas and no spaces.
Constraints
0 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9
Examples
Example 1
Input: compress_ranges([1, 4, 5, 2, 3, 9, 8, 11])
Output: '1-5,8-9,11'
Example 2
Input: compress_ranges([3, 3, 3])
Output: '3'
Example 3
Input: compress_ranges([])
Output: ''
Hints
Hint 1
Start by removing duplicate elements and sorting the unique values in ascending order.
Hint 2
Traverse the sorted unique list while keeping track of the start and current end of the active continuous interval.
Hint 3
When a sequence breaks (i.e., current number > previous number + 1), format and append the current interval, then start a new interval. Don't forget to append the final interval after the loop finishes.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires merging consecutive numbers into representative range strings after sorting and deduplicating.
- Preprocessing: Convert the input array
numsto asetto eliminate duplicates, then sort the unique values. - Interval Traversal: Iterate through the sorted list maintaining two pointers or tracking variables:
start(the beginning of the current interval) andprev(the last number seen in the current interval).- If the current number equals
prev + 1, extend the active interval by updatingprev. - Otherwise, the contiguous sequence is broken. Format the completed interval (
"start"ifstart == prev, or"start-prev"otherwise), append it to a list of segments, and reassign bothstartandprevto the current number.
- If the current number equals
- Final Flush: After completing the loop, format and append the last pending interval.
- Output Assembly: Join all formatted interval strings with a comma separator.
Complexity
- Time Complexity: $O(N \log N)$ where $N$ is the number of elements in
nums. Converting to a set takes $O(N)$ time, sorting $U \le N$ unique elements takes $O(U \log U)$ time, and the linear scan takes $O(U)$ time. - Space Complexity: $O(N)$ auxiliary space to store the deduplicated sorted array and output string components.
Python Reference Solution
from typing import List
def compress_ranges(nums: List[int]) -> str:
if not nums:
return ""
values = sorted(set(nums))
result = []
start = prev = values[0]
for value in values[1:]:
if value != prev + 1:
result.append(str(start) if start == prev else f"{start}-{prev}")
start = value
prev = value
result.append(str(start) if start == prev else f"{start}-{prev}")
return ",".join(result)