Ctrl K

Compress Consecutive Runs

Easy
A warehouse logs the box numbers it ships and wants them written compactly. You are given a strictly increasing list of distinct integers ids. Split it into maximal runs of consecutive numbers with no gaps (each next number is exactly 1 more than the previous one). Write each run as a string: - "a->b" if the run starts at a and ends at b, with a != b; - "a" if the run is a single number. Return the strings in increasing order. Every number in ids must belong to exactly one run, and no run may contain a number that is not in ids.
Example 1
ids=[3, 4, 5, 6, 10, 12, 13] → ['3->6', '10', '12->13']

Numbers 3 to 6 are consecutive and collapse into "3->6", 10 stands alone, and 12, 13 give "12->13".

Example 2
ids=[-2, 0, 1] → ['-2', '0->1']

-1 is missing between -2 and 0, so -2 is a range of its own.

Example 3
ids=[] → []

No numbers, no ranges.

Constraints
  • 0 ≤ len(ids) ≤ 20
  • -2³¹ ≤ ids[i] ≤ 2³¹ - 1
  • The values in ids are distinct and sorted in increasing order
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPair With a Target Sum EasySqueeze Repeats Out of a Sorted Array EasyDrop the Unwanted Value EasySlot on a Sorted Shelf EasyAdd One to a Digit Array Easy
loading Python…
Input
ids=[3, 4, 5, 6, 10, 12, 13]
Expected
['3->6', '10', '12->13']

Run checks the first 3 tests in your browser. Submit checks all 97 tests on the server, hidden ones included.