Summary Ranges (LeetCode 228): Solution and Explanation

Easy
Array

You get a sorted array of unique integers. Group the numbers into the fewest ranges of consecutive integers and return them in order, written as "a->b" for a range with several numbers and "a" for a single number.

Intuition

Because the array is sorted and has no duplicates, two neighbours belong to the same range exactly when the second one is the first plus one. Any bigger difference means some integer between them is missing, so a range has to end there.

That turns the problem into cutting the array at its gaps. Walk left to right, remember where the current run started, and keep stepping while the next value is one more than the current one. The moment that test fails, the run is finished and can be written down.

Every index is either inside the run being grown or starts the next one, so a single pass over the array is enough. There is nothing to sort, search or merge.

Approach: Grow each run with one pointer

  1. Create an empty result list and set i = 0.
  2. While i < len(nums), save start = nums[i] as the first value of a new run.
  3. While i + 1 is in bounds and nums[i + 1] == nums[i] + 1, move i forward. The run now ends at nums[i].
  4. If start == nums[i] the run is one number, so append str(start). Otherwise append "start->nums[i]".
  5. Move i one step past the run and repeat. Return the result list when i reaches the end.

Step-by-step example

nums = [0,1,2,4,5,7]
  1. i = 0, start = 0. nums[1] = 1 is 0 + 1, so i moves to 1. nums[2] = 2 is 1 + 1, so i moves to 2.
  2. nums[3] = 4 is not 2 + 1, so the run stops at 2. Append "0->2" and move i to 3.
  3. start = 4. nums[4] = 5 is 4 + 1, so i moves to 4. nums[5] = 7 is not 6, so append "4->5" and move i to 5.
  4. start = 7. There is no next number, so the run is just 7. Append "7" and move i to 6.
  5. i equals the length, so the loop ends and the answer is ["0->2","4->5","7"].

Code: Python, Java, C++

1class Solution:
2    def summaryRanges(self, nums: List[int]) -> List[str]:
3        res = []
4        i = 0
5        while i < len(nums):
6            start = nums[i]
7            while i + 1 < len(nums) and nums[i + 1] == nums[i] + 1:
8                i += 1
9            if start == nums[i]:
10                res.append(str(start))
11            else:
12                res.append(f"{start}->{nums[i]}")
13            i += 1
14        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

The index i only moves forward, and each step does constant work, so every element is looked at a constant number of times.

Space

O(1)

Apart from the output list, only the index and the run start are stored.

Other approaches

Two indices with a for loop (time O(n), space O(1))

Loop over every index and close the current run whenever i is the last index or nums[i + 1] != nums[i] + 1, then set the next start to i + 1. It does the same work with a single loop instead of a nested one.

Compare against the expected value (time O(n), space O(1))

Keep the run start index s and note that inside a run nums[i] - nums[s] == i - s. Close the run as soon as that equation breaks. It avoids computing nums[i] + 1, but the subtraction can overflow in the same way, so it needs a wider type too.

Common mistakes

  • Overflow on nums[i] + 1 when nums[i] is 2^31 - 1. In Java, C++ and C#, widen to a 64-bit type before adding, or compare nums[i + 1] - 1 == nums[i], which is safe because nums[i + 1] is always above the minimum value.
  • Forgetting the last run. If the run is closed only when a gap is found, the run that reaches the end of the array never gets written.
  • Writing a single number as "a->a" instead of "a".
  • Returning null instead of an empty list when nums is empty.

Frequently asked questions

Why is checking nums[i + 1] == nums[i] + 1 enough?

The array is sorted with unique values, so the next value is always larger. If it is exactly one larger, no integer is skipped and the run continues. If it is larger by more, at least one integer is missing and the range must end.

What should be returned for an empty array?

An empty list. The outer loop never runs, so the result list stays empty.

What is the time and space complexity of Summary Ranges?

O(n) time because the index only moves forward, and O(1) extra space besides the output.

Does the output order matter?

Yes. The ranges must be listed in sorted order, which the left to right scan produces automatically.