KatInterview

Summarize Integer Ranges into String

Greedy & IntervalsAuto-graded · 26 test cases
EasyAuto-gradedGreedy & Intervalsarrayssortingintervals

Last 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

  1. Ignore duplicate integer values.
  2. The formatted ranges must appear in strictly ascending numerical order.
  3. 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").
  4. If two or more adjacent integers form a continuous sequence [x, x+1, ..., y], represent the sequence as "x-y".
  5. 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.