Problem 224326 · medium · Phase 02 Linear Data Structures

Squash Number Lists into Ranges

strings · parsing · compression

Write compress_ranges(s) where s is a comma-separated list of distinct non-negative integers in increasing order (spaces around numbers are allowed). Return a string in which every run of three or more consecutive integers is written as first-last, while shorter runs stay as individual numbers. Output items are separated by commas without spaces. An empty input gives "".

Examples

Input:  s = "1,2,3,5,7,8,9"
Output: "1-3,5,7-9"

Input:  s = "1,2,4"
Output: "1,2,4"
Explanation: 1,2 is a run of only two, so it is not collapsed.

Input:  s = ""
Output: ""

Constraints

  • 0 <= len(s) <= 10**5, at most 104 numbers, each below 109
  • Target: O(n) time

Goals

  • Parse a delimited list of integers, tolerating spaces
  • Detect runs of consecutive values
  • Format runs differently depending on their length
Starting Python…