Compress Consecutive Integer Ranges
Given an unsorted list of integers, sort the distinct values and render each maximal run of consecutive values as either one integer or start-end. Join rendered runs with commas and no spaces.
Function Signature
compress_ranges(values: list[int]) -> str
Valid Input Domain
Values may be empty and may contain negative, zero, positive, or duplicate 32-bit signed integers.
Exact Output Semantics
Return one canonical string. Duplicate values appear once. Runs are ordered numerically. A run of length one is written as its value; a longer run is written as start-end, including forms such as -3--1. Empty input returns the empty string.
Constraints
-
0 <= values.length <= 200,000.
-
-2^31 <= values[i] <= 2^31 - 1.
-
The implementation may sort in place and should avoid an additional set proportional to input size.
Public Examples
Example 1
Input: values = [1, 2, 5, 3, 6, 9]
Output: "1-3,5-6,9"
Sorting yields runs 1 through 3, 5 through 6, and the singleton 9.
Example 2
Input: values = [-3, -2, -2, -1, 2, 3]
Output: "-3--1,2-3"
The duplicate -2 is ignored, and negative range punctuation remains unambiguous under the specified format.
Hints
-
After sorting, compare each value with the last distinct value rather than the immediately preceding array slot.
-
Delay emitting a run until a gap appears or the input ends.