1210. Page Range Normaliser

Medium3.5 points estimatedStringSortingIntervals

A print dialog lets people type which pages they want, such as 5, 1-3, 4, 9-7, and the app must turn that into one clean canonical list before sending the job. The string spec is a comma-separated list of tokens. Each token is either a single page a or a range a-b, and a range may be written in descending order, so 9-7 means pages 7 to 9. Spaces may appear around tokens and around hyphens; ignore them.

Collect every requested page, merge ranges that overlap or touch (page 3 and page 4 touch), and return the canonical form. The merged runs go in ascending order separated by single commas with no spaces. A run of two or more pages is written a-b and a single page is written alone. For example 5, 1-3, 4, 9-7 becomes 1-5,7-9. Aim for O(k log k) time for k tokens.

Example 1

Input:
spec = "5, 1-3, 4, 9-7"
Output:
"1-5,7-9"
Explanation:

Pages 1-3 and 4 and 5 form one run 1-5, and 9-7 is the range 7-9, so the answer is 1-5,7-9.

Example 2

Input:
spec = "10,12,11"
Output:
"10-12"
Explanation:

The three pages 10, 11 and 12 touch, so they merge into 10-12.

Example 3

Input:
spec = "2, 20, 8-8"
Output:
"2,8,20"
Explanation:

The range 8-8 is just page 8, and no pages touch, so the answer is 2,8,20.

Constraints

1 ≤ spec.length ≤ 104

1 ≤ page ≤ 109

spec is well-formed: at least one token, no empty tokens

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(k log k)
Space
O(k)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…