Summary Ranges
Given a sorted unique integer array nums, return the smallest sorted list of ranges that cover every number in the array exactly.
Intuition
Because the array is sorted and has no duplicates, consecutive integers form contiguous runs. Walk through the array and track where each run starts. As long as the next element is exactly one more than the current, the run continues. The moment the next element breaks the sequence (or you reach the end), close the current range and start a new one. Each range is either a single number or start->end.
When a sorted array asks you to group consecutive sequences, the pattern is a single pass that tracks the start of each run and closes it when the sequence breaks. The format varies — here it is range strings — but the grouping logic is always the same: compare each element to its successor.
Approach
Track the start of each consecutive run
Initialize a pointer start at the first element. Walk through the array with index i. As long as nums[i+1] == nums[i] + 1, the run continues — just advance i.
Close the range when the run breaks
When nums[i+1] != nums[i] + 1 (or i reaches the last index), the run from nums[start] to nums[i] is complete. If start == i, it is a single number — format as str(nums[start]). Otherwise, format as str(nums[start]) + '->' + str(nums[i]). Append to the result and set start = i + 1.
Return the collected ranges
After the loop, all ranges have been collected. Time is O(n) — single pass. Space is O(1) beyond the output list.
Solution
Common pitfalls
Using nums[i+1] - nums[i] == 1 without bounds checking
for i in range(len(nums)):
if nums[i+1] - nums[i] == 1:for i in range(len(nums)):
if i + 1 < len(nums) and nums[i+1] - nums[i] == 1:On the last element, nums[i+1] is an index-out-of-bounds error. The bounds check ensures you only compare when a next element exists.
Formatting single-number ranges with an arrow
result.append(f'{nums[start]}->{nums[i]}')if start == i:
result.append(str(nums[start]))
else:
result.append(f'{nums[start]}->{nums[i]}')A range like 5->5 is redundant and does not match the expected output format. Single numbers should be formatted without the arrow.
Resetting start to i instead of i + 1 after closing a range
start = i
start = i + 1
Index i was the end of the last range. The new range starts at i + 1. Setting start = i includes the last element of the previous range in the next range, duplicating it.
Edge cases
The loop does not run. Return an empty list.
One range: just that element as a string.
One range covering the entire array: nums[0]->nums[-1].