Problem · Array
Compress Consecutive Integer Ranges
Learn this problemProblem statement
Given an unsorted integer array nums, return a compact string describing its distinct values in ascending order.
Sort the values and split them into maximal runs of consecutive integers. Format a run containing at least two distinct values as start-end, format a singleton as its decimal value, and join the pieces with commas and no spaces. Repeated occurrences of a value belong to the same run and appear only once in the result. Return the empty string for an empty array.
Function
compressRanges(nums: int[]) → StringExamples
Example 1
nums = [1,2,5,3,6,9]return = "1-3,5-6,9"Sorting gives [1,2,3,5,6,9]. The maximal runs are 1 through 3, 5 through 6, and the singleton 9.
Example 2
nums = [1,3,5,7,9]return = "1,3,5,7,9"No two distinct values are consecutive, so every value is a singleton.
Example 3
nums = [-3,-2,-2,-1,2,3]return = "-3--1,2-3"The duplicate -2 is ignored. The two maximal runs are -3 through -1 and 2 through 3.
Constraints
0 <= nums.length <= 200000.- Every element fits in a signed 32-bit integer.
- The method may reorder
nums. - Repeated values are emitted once.