Summary Ranges
Summary Ranges is LeetCode 228 (Easy). You get a sorted unique integer array nums. Cover every number in it with as few ranges as possible and return those ranges in order, as strings.
- A range of two or more numbers is written
"a->b". - A range of one number is written
"a". - The array can be empty. Its values can sit anywhere in the 32-bit range, including the very ends.
- 0 <= nums.length <= 20
- -2³¹ <= nums[i] <= 2³¹ - 1
- All the values of nums are unique.
- nums is sorted in ascending order.
Intuition
Because the array is sorted and has no repeats, the numbers of one range always sit side by side. A range is a run of neighbours where each value is exactly one more than the value before it, and the first neighbour that skips ahead ends the run.
So one pass from the left finds every range. Remember where the current run starts, keep moving while the next value is one more, and write the run out when it stops. Then start a new run on the next index.
The result is the fewest ranges possible: between two runs at least one number is missing, so no two of them could be joined.
Grouping a sorted array into ranges of consecutive numbers is a single scan with two indices, one at the start of the current run and one at its end.
Approach
Before reading on, take [0,1,2,4,5,7] and decide, for each neighbour pair, whether the pair keeps a run going or ends it. Then decide how a run of one number should be written. Aim for one pass.
Open a run at index i
Loop while i < n, and at the top of each loop set start = i. The previous range ended just before i, so nums[i] is the first number of a new range.
Grow the run while the next value is one more
While i + 1 < n and nums[i + 1] == nums[i] + 1, move i forward. The bound check comes first, so the code never reads past the end, and i stops on the last value of the run.
Write the run as a string
If start == i the run holds one value, so append str(nums[i]). Otherwise append nums[start], then ->, then nums[i]. Both forms use the values at those indices, not the indices themselves.
Step past the run
Set i += 1 so the next loop opens a run on the first value after the gap. The last run needs no extra code: the inner loop stops at the end of the array, and the run is written before the outer loop checks i < n again.
Code in Python, C++ and Java
i < n is false at once, so the loop body never runs.Common pitfalls
Writing a range only when a gap appears
for i in range(1, n):
if nums[i] != nums[i - 1] + 1:
result.append(...)
start = iwhile i < n:
... # write every run when its inner loop stopsThe last run has no gap after it, so it is never written. On [0,1,2,4,5,7] this returns ["0->2", "4->5"] and loses "7". A for-loop version must write the open run once more after the loop.
Subtracting neighbours in C++
if (nums[i + 1] - nums[i] == 1)
if (nums[i + 1] == nums[i] + 1)
On [-2147483648, 2147483647] the true difference does not fit in an int, and signed overflow is undefined behaviour in C++. The + 1 form is safe: since the array is sorted and unique, the largest int can only be the last value, and the bound check stops before + 1 is applied to it.
Writing a single number as a range
result.append(f"{nums[start]}->{nums[i]}")if start == i:
result.append(str(nums[i]))A run of one value must be the bare number. On [0,2] the always-arrow version returns ["0->0", "2->2"] instead of ["0", "2"].
Edge cases
[]The outer loop never runs, so the answer is an empty list.
[-3,-2,-1,1]-2 is -3 + 1, so the test works the same below zero. The answer is ["-3->-1", "1"]; the minus signs come from the number formatting.
Complexity
i forward n times in total. Space counts only the two indices; the output list itself is not extra space.Summary Ranges FAQ
What if the array is not sorted or has repeats?
Sort it first, which makes the whole thing O(n log n). With repeats, treat a value equal to the previous one as part of the same run, or remove duplicates before the scan.
Can the end of a long run be found faster than one step at a time?
Yes. With unique sorted values, nums[start..j] is one run exactly when nums[j] - nums[start] == j - start, so a binary search can find where the run ends. That helps only when runs are long; for 20 numbers the plain scan is simpler.
How does this relate to Missing Ranges?
Missing Ranges (LeetCode 163) reports the gaps instead of the runs. It walks the same neighbour pairs and writes a range whenever two neighbours differ by more than one.