Summary Ranges (LeetCode 228): Solution and Explanation
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
- Create an empty result list and set
i = 0. - While
i < len(nums), savestart = nums[i]as the first value of a new run. - While
i + 1is in bounds andnums[i + 1] == nums[i] + 1, moveiforward. The run now ends atnums[i]. - If
start == nums[i]the run is one number, so appendstr(start). Otherwise append"start->nums[i]". - Move
ione step past the run and repeat. Return the result list whenireaches the end.
Step-by-step example
nums = [0,1,2,4,5,7]
- 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.
- nums[3] = 4 is not 2 + 1, so the run stops at 2. Append "0->2" and move i to 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.
- start = 7. There is no next number, so the run is just 7. Append "7" and move i to 6.
- 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 res1class Solution {
2 public List<String> summaryRanges(int[] nums) {
3 List<String> res = new ArrayList<>();
4 int i = 0;
5 while (i < nums.length) {
6 int start = nums[i];
7 while (i + 1 < nums.length && nums[i + 1] == (long) nums[i] + 1) {
8 i++;
9 }
10 if (start == nums[i]) {
11 res.add(String.valueOf(start));
12 } else {
13 res.add(start + "->" + nums[i]);
14 }
15 i++;
16 }
17 return res;
18 }
19}1class Solution {
2public:
3 vector<string> summaryRanges(vector<int>& nums) {
4 vector<string> res;
5 int i = 0, n = nums.size();
6 while (i < n) {
7 int start = nums[i];
8 while (i + 1 < n && nums[i + 1] == (long long) nums[i] + 1) {
9 i++;
10 }
11 if (start == nums[i]) {
12 res.push_back(to_string(start));
13 } else {
14 res.push_back(to_string(start) + "->" + to_string(nums[i]));
15 }
16 i++;
17 }
18 return res;
19 }
20};Time and space complexity
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.
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] + 1whennums[i]is 2^31 - 1. In Java, C++ and C#, widen to a 64-bit type before adding, or comparenums[i + 1] - 1 == nums[i], which is safe becausenums[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
nullinstead of an empty list whennumsis 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.