LeetCode #228 Easy

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.
Constraints
  • 0 <= nums.length <= 20
  • -2³¹ <= nums[i] <= 2³¹ - 1
  • All the values of nums are unique.
  • nums is sorted in ascending order.
arrays
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def summaryRanges(self, nums):
▶3 result = []
▶4 n = len(nums)
▶5 i = 0
▶6 while i < n:
▶7 start = i
▶8 while i + 1 < n and nums[i + 1] == nums[i] + 1:
▶9 i += 1
▶10 if start == i:
▶11 result.append(str(nums[i]))
▶12 else:
▶13 result.append(f"{nums[start]}->{nums[i]}")
▶14 i += 1
▶15 return result
nums012457rangesnone yetsorted, no repeats → one pass, left to right
n6
resultempty list
The array is sorted and has no repeated values, so the numbers of any one range sit side by side. One pass from the left finds every range.
nums012457start, irangesnone yetnew run starts at 0
start0value 0
The first value opens the first range.
nums+1012457startirangesnone yet1 is one more than 0 → run grows
i1value 1
The next value is exactly one more, so no whole number is missing between them and 1 joins the run from 0.
nums+1+1012457startirangesnone yet2 is one more than 1 → run grows
i2value 2
The next value is exactly one more, so no whole number is missing between them and 2 joins the run from 0.
nums+1+1gap012457startirangesnone yet4 is not one more than 2 → run ends
i2last value of the run
3 is missing from the array, so 4 cannot be in the same range. The run ends at 2.
nums+1+1gap012457startiranges0->2write "0->2"
range"0->2"
The run covers 0 to 2, so it is written 0->2. The next run starts on the value after the gap.
nums+1+1gap012457start, iranges0->2new run starts at 4
start3value 4
The previous range ended just before index 3, so 4 opens a new one.
nums+1+1gap+1012457startiranges0->25 is one more than 4 → run grows
i4value 5
The next value is exactly one more, so no whole number is missing between them and 5 joins the run from 4.
nums+1+1gap+1gap012457startiranges0->27 is not one more than 5 → run ends
i4last value of the run
6 is missing from the array, so 7 cannot be in the same range. The run ends at 5.
nums+1+1gap+1gap012457startiranges0->24->5write "4->5"
range"4->5"
The run covers 4 to 5, so it is written 4->5. The next run starts on the value after the gap.
nums+1+1gap+1gap012457start, iranges0->24->5new run starts at 7
start5value 7
The previous range ended just before index 5, so 7 opens a new one.
nums+1+1gap+1gap012457start, iranges0->24->5no value after 7 → run ends
i5last value of the run
There is no next value, so the run stops at 7. The same check that stops it also keeps the code from reading past the end.
nums+1+1gap+1gap012457start, iranges0->24->57one value → write "7"
range"7"
The run holds a single value, so it is written as the bare number 7, not as 7->7.
nums+1+1gap+1gap012457ranges0->24->57answer: 3 ranges
result"0->2", "4->5", "7"
Every value is in exactly one range, in sorted order. No two ranges can be merged, because a gap of at least one missing number separates each pair, so this is the fewest ranges possible.
05

Common pitfalls

Writing a range only when a gap appears

✗ Wrong
for i in range(1, n):
    if nums[i] != nums[i - 1] + 1:
        result.append(...)
        start = i
✓ Right
while i < n:
    ...  # write every run when its inner loop stops

The 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++

✗ Wrong
if (nums[i + 1] - nums[i] == 1)
✓ Right
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

✗ Wrong
result.append(f"{nums[start]}->{nums[i]}")
✓ Right
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"].

06

Edge cases

Empty array, []

The outer loop never runs, so the answer is an empty list.

Negative numbers, [-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.

07

Complexity

Time
O(n)
Space
O(1)
The inner and outer loops together move i forward n times in total. Space counts only the two indices; the output list itself is not extra space.
08

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.