208/670

208. Summary Ranges

Easy

You are given nums, an array of unique integers sorted in strictly increasing order. Compress it into the shortest list of ranges that covers exactly the numbers in the array: every element of nums falls inside exactly one range, and no range contains a number that is missing from nums.

Return the ranges in ascending order as strings, writing a run from a up to b as "a->b" when b > a, and a run of a single number simply as "a".

For example, [0, 1, 2, 4] compresses to ["0->2", "4"] — the run 0..2 plus the lone 4.

Example 1 on a number lineThe sorted values 0, 1, 2, 4, 5, 7 form three maximal consecutive runs; the missing 3 and 6 are where the ranges split.
0123 4567 "0->2" "4->5" "7" 3 and 6 are missing, so the chains break there

Example 1:

Input: nums = [0, 1, 2, 4, 5, 7]

Output: ["0->2", "4->5", "7"]

Explanation: 0,1,2 form one consecutive run, 4,5 form another, and 7 stands alone.

Example 2:

Input: nums = [0, 2, 3, 4, 6, 8, 9]

Output: ["0", "2->4", "6", "8->9"]

Explanation: 1 is missing, so 0 is alone; 2,3,4 run together; 6 is alone; 8,9 run together.

Constraints:

  • 0 ≤ n ≤ 10⁴
  • -2³¹ ≤ nums[i] ≤ 2³¹ - 1
  • All values are unique
  • nums is sorted in strictly increasing order

Hints:

A range ends exactly where consecutiveness breaks: when nums[i+1] is not nums[i] + 1, whatever run you were building is finished.

Walk the array once with a pointer to the start of the current run. Extend while the next value is exactly one more; when it is not (or the array ends), emit either "start->end" or just "start" and begin a new run.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [0, 1, 2, 4, 5, 7]

Expected output: ["0->2", "4->5", "7"]