You get a sorted array nums of distinct integers. Group the values into ranges of consecutive integers, where each range is as long as it can be, and return them in order.
Write a range that holds one value as just that value, like "8". Write a longer range as its first and last values joined by an arrow, like "2->5".
Example 1
Input: nums = [-3, -2, -1, 4, 6, 7] Output: ["-3->-1", "4", "6->7"] Why: -3, -2, -1 run together; 4 stands alone; 6, 7 run together
2 more examples and the constraints
Example 2
Input: nums = [1, 3, 5] Output: ["1", "3", "5"] Why: no two values are one apart
Example 3
Input: nums = [] Output: [] Why: no values, so no ranges
Constraints
- 0 ≤ nums.length ≤ 20
- −2³¹ ≤ nums[i] ≤ 2³¹ − 1
- nums is sorted in increasing order and has no repeats
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Look up neighbours in a setO(n)
- One scan with two pointersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20 values | Verdict |
|---|---|---|---|
| Look up neighbours in a set | O(n) | Passes; hashing and extra memory | |
| One scan with two pointers | O(n) | Best; plain comparisons |
n = length of nums.
Edge cases to test
- Empty array. Return an empty list, not
[""]. - One value.
[5]gives["5"], with no arrow. - A run at the end. The last range is only written when the scan runs out of cells; do not forget it.
- Values at the int limits.
[-2147483648, 2147483647]must give two single ranges, not overflow into one.
Common mistakes
- Checking
nums[j + 1] - nums[j] == 1, which overflows for −2³¹ and 2³¹ − 1. - Forgetting to write the final range after the loop ends.
- Writing a single value as
"4->4"instead of"4".
How to talk through it
- 1Clarify. Is the array sorted with no repeats? Can it be empty? What is the exact output format?
- 2Name the rule. A range breaks wherever the next value is not the current value plus one.
- 3Mention the set idea. It works for unsorted input but needs O(n) memory you do not need here.
- 4Code the scan. Two pointers:
iopens a range,jextends it, then jumpitoj + 1. - 5Test out loud. Run an empty array, a single value and the int limits before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?