Skip to content

Summary Ranges

You are given a sorted unique integer array nums. A range is defined as a contiguous sequence of elements. Return a list of the smallest set of ranges that cover all the numbers in the array exactly. That is, each element in nums is covered by exactly one range, and there is no integer x such that x is in one of the ranges but not in nums.

InputOutputExplanation
[0, 1, 2, 4, 5, 7]["0->2", "4->5", "7"]Three ranges: 0-2, 4-5, and single 7
[0, 2, 3, 4, 6, 8, 9]["0", "2->4", "6", "8->9"]Four ranges with mixed single and multi
[][]Empty input returns empty output
  • 0 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
  • All the values of nums are unique.
  • nums is sorted in ascending order.
ApproachTimeSpaceNotes
SimulationO(n)O(1)Single pass, build result on the fly
Two-PointerO(n)O(1)Cleaner boundary detection, explicit pointers

Both approaches have optimal time complexity. Choose based on code clarity preference.

  • Pick Simulation if you want a straightforward, single-loop implementation.
  • Pick Two-Pointer if you prefer explicit boundary management.
Most Direct
Simulation
O(n) time · O(1) space
Explicit Boundaries
Two-Pointer
O(n) time · O(1) space
★ Recommended

Iterate through the array once. Track the start of the current range. When a gap is found (consecutive check fails), finalize the current range and start a new one.

⏱ Time O(n) Single pass 💾 Space O(1) Only pointers

Input: nums = [0, 1, 2, 4, 5, 7]

Stepinums[i]Current RangeAction
1--start=0Initialize with first element
2110-1Consecutive, continue
3220-2Consecutive, continue
434-Gap found! Save “0->2”, start=4
5454-5Consecutive, continue
657-Gap found! Save “4->5”, start=7
7---End of array, save “7”
function summaryRanges(nums):
if nums is empty:
return []
result = []
start = nums[0]
for i from 1 to len(nums) - 1:
if nums[i] != nums[i-1] + 1:
// Gap found, finalize range
if start == nums[i-1]:
result.append(str(start))
else:
result.append(str(start) + "->" + str(nums[i-1]))
start = nums[i]
// Add final range
if start == nums[-1]:
result.append(str(start))
else:
result.append(str(start) + "->" + str(nums[-1]))
return result
summary_ranges_simulation.py
from typing import List
def summary_ranges(nums: List[int]) -> List[str]:
"""
Simulation approach: iterate through and build ranges as we go.
Time: O(n), Space: O(1) excluding output
"""
if not nums:
return []
result = []
start = nums[0]
for i in range(1, len(nums)):
# If current number is not consecutive, finalize the range
if nums[i] != nums[i - 1] + 1:
if start == nums[i - 1]:
result.append(str(start))
else:
result.append(f"{start}->{nums[i - 1]}")
start = nums[i]
# Add the last range
if start == nums[-1]:
result.append(str(start))
else:
result.append(f"{start}->{nums[-1]}")
return result
print(summary_ranges([0, 1, 2, 4, 5, 7])) # ["0->2","4->5","7"]
print(summary_ranges([0, 2, 3, 4, 6, 8, 9])) # ["0","2->4","6","8->9"]
🎯 Interview Favourite

Maintain explicit left and right pointers. The right pointer advances; when a gap is detected, both pointers define the current range.

⏱ Time O(n) Single pass 💾 Space O(1) Only pointers

Input: nums = [0, 2, 3, 4, 6, 8, 9]

Stepleftrightnums[left]nums[right]CheckAction
10000Next (2) != 1Save “0”, left=1
21122Next (3) == 3Continue
31223Next (4) == 4Continue
41324Next (6) != 5Save “2->4”, left=4
54466Next (8) != 7Save “6”, left=5
65588Next (9) == 9Continue
75689EndSave “8->9”
function summaryRanges(nums):
if nums is empty:
return []
result = []
left = 0
for right from 0 to len(nums) - 1:
// Check if this is the last element or next breaks sequence
if right == len(nums) - 1 or nums[right + 1] != nums[right] + 1:
if left == right:
result.append(str(nums[left]))
else:
result.append(str(nums[left]) + "->" + str(nums[right]))
left = right + 1
return result
summary_ranges_pointers.py
from typing import List
def summary_ranges(nums: List[int]) -> List[str]:
"""
Two-pointer approach: explicitly track start and end pointers.
Time: O(n), Space: O(1) excluding output
"""
if not nums:
return []
result = []
left = 0
for right in range(len(nums)):
# Check if next element breaks the sequence
if right == len(nums) - 1 or nums[right + 1] != nums[right] + 1:
if left == right:
result.append(str(nums[left]))
else:
result.append(f"{nums[left]}->{nums[right]}")
left = right + 1
return result
print(summary_ranges([0, 1, 2, 4, 5, 7])) # ["0->2","4->5","7"]
print(summary_ranges([0, 2, 3, 4, 6, 8, 9])) # ["0","2->4","6","8->9"]
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
summary_ranges_optimized.py
"""
Solution for Summary Ranges
"""
def solve():
"""Implementation for approach 3 of Summary Ranges"""
pass
if __name__ == "__main__":
print("Solution ready")