Compress Consecutive Integer Ranges
DocuSignSoftware Engineer · OnsiteLast updated
Tests array manipulation, sorting, deduplication, and range-grouping logic to produce a compact string representation of consecutive numbers.
Compress Consecutive Integer Ranges
Given an unsorted list of integers nums, compress the values into a canonical comma-separated string of maximal consecutive ranges.
Rules
- The output must be sorted in ascending order.
- Duplicate values should be ignored.
- If a number does not have an adjacent consecutive neighbor, represent it as a single integer (e.g.,
"5"). - If two or more integers form a contiguous sequence
[a, a+1, ..., b], represent the sequence as"a-b".
Function Signature
def compress_ranges(nums: list[int]) -> str:
pass
Input and Output Format
- Input: A list of integers
nums. - Output: A single string with compressed ranges separated by commas, with no spaces.
Constraints
0 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9
Examples
Example 1:
Input: nums = [1, 4, 5, 2, 3, 9, 8, 11]
Output: "1-5,8-9,11"
Explanation:
After sorting and removing duplicates, the numbers are [1, 2, 3, 4, 5, 8, 9, 11].
- 1 through 5 form a contiguous range: "1-5"
- 8 and 9 form a contiguous range: "8-9"
- 11 is standalone: "11"
Joined by commas: "1-5,8-9,11"
Example 2:
Input: nums = [3, 3, 3]
Output: "3"
Explanation: Duplicates are removed, leaving only the single value 3.
Example 3:
Input: nums = []
Output: ""
Explanation: An empty input produces an empty string.
Edge Cases to Consider
- Empty input array.
- Single element array.
- Arrays with negative numbers and sequences spanning across zero (e.g.,
[-2, -1, 0, 1]). - Arrays consisting entirely of duplicate values.
Hints
Hint 1
Remove duplicates and sort the unique numbers in ascending order before scanning for contiguous segments.
Hint 2
Track the starting number and current number of a segment as you iterate through the sorted values.
Hint 3
Whenever a number is not equal to the previous number plus one, close the previous range and begin a new one.
Follow-up questions
- How would you handle a continuous data stream of incoming integers where you need to query the current compressed representation at any time?
- How would your approach change if a range requires at least three consecutive values to be compressed (e.g., `1, 2` remains `"1,2"` but `1, 2, 3` becomes `"1-3"`)?
- If the input numbers are distributed across multiple files that cannot fit in memory at once, how would you design an external sorting and compression pipeline?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.