InterviewPrepKit

Home / Coding / Arrays & Hashing

Summary Ranges

easy Original ↗
Solving tips
  • Exploit the sorted-distinct input: a single linear pass finds maximal consecutive runs, no inner loop needed.
  • Remember only where the current run started; element i is a run's right edge when i is the last index OR nums[i]+1 != nums[i+1] — emit there and reset start. O(n) time, O(1) extra space.
  • Format the emit with a start==i branch: single number 'a' for singletons, 'a->b' otherwise.
  • Pitfall: flush the final run (treat last index as an edge) or it gets dropped, and handle the empty array returning [].

Problem

You’re given a sorted integer array nums with all elements distinct. Compress it into the shortest possible list of range strings that together cover exactly the numbers present:

  • a run of consecutive integers a, a+1, ..., b (with a != b) becomes the string "a->b";
  • an isolated number a becomes just "a".

Return the ranges in ascending order.

Examples

  • Input: nums = [0, 1, 2, 4, 5, 7] → Output: ["0->2", "4->5", "7"] 0–2 are consecutive, 4–5 are consecutive, 7 stands alone.
  • Input: nums = [0, 2, 3, 4, 6, 8, 9] → Output: ["0", "2->4", "6", "8->9"] Runs break wherever the gap between neighbors exceeds 1.
  • Input: nums = [-3, -2, -1, 5] → Output: ["-3->-1", "5"] Negative numbers form runs the same way; -3,-2,-1 is one run.

Constraints

  • 0 <= len(nums) <= 20
  • -2^31 <= nums[i] <= 2^31 - 1
  • All values are unique and nums is sorted ascending

A single O(n) pass is expected — the sortedness hands you the runs.

Think about it first

Hint 1 In a sorted array of distinct integers, how do you recognize that a consecutive run *ends* at index i?
Hint 2 You only ever need to remember one thing while scanning: where the current run started.
Hint 3 Keep `start`. Walk i through the array; whenever `nums[i] + 1` differs from the next element (or the array ends), emit `start..nums[i]` — as one number if they're equal, as `"start->end"` otherwise — and begin a new run at the next element.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.