Summary Ranges
Problem Statement
Section titled “Problem Statement”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.
Examples
Section titled “Examples”| Input | Output | Explanation |
|---|---|---|
[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 |
Constraints
Section titled “Constraints”0 <= nums.length <= 10^4-2^31 <= nums[i] <= 2^31 - 1- All the values of
numsare unique. numsis sorted in ascending order.
Real-World Applications
Section titled “Real-World Applications”Complexity Comparison
Section titled “Complexity Comparison”| Approach | Time | Space | Notes |
|---|---|---|---|
| Simulation | O(n) | O(1) | Single pass, build result on the fly |
| Two-Pointer | O(n) | O(1) | Cleaner boundary detection, explicit pointers |
Both approaches have optimal time complexity. Choose based on code clarity preference.
Which approach should you learn first?
Section titled “Which approach should you learn first?”- Pick Simulation if you want a straightforward, single-loop implementation.
- Pick Two-Pointer if you prefer explicit boundary management.
Approach 1: Simulation
Section titled “Approach 1: Simulation”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.
Step-by-step Example
Section titled “Step-by-step Example”Input: nums = [0, 1, 2, 4, 5, 7]
| Step | i | nums[i] | Current Range | Action |
|---|---|---|---|---|
| 1 | - | - | start=0 | Initialize with first element |
| 2 | 1 | 1 | 0-1 | Consecutive, continue |
| 3 | 2 | 2 | 0-2 | Consecutive, continue |
| 4 | 3 | 4 | - | Gap found! Save “0->2”, start=4 |
| 5 | 4 | 5 | 4-5 | Consecutive, continue |
| 6 | 5 | 7 | - | Gap found! Save “4->5”, start=7 |
| 7 | - | - | - | End of array, save “7” |
Pseudocode
Section titled “Pseudocode”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 resultSolution Code
Section titled “Solution Code”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"]// Summary Ranges - SIMULATION// Problem #228
// Implementation here// Summary Ranges - SIMULATION// Problem #228
// Implementation here// Summary Ranges - SIMULATION// Problem #228
// Implementation here// Summary Ranges - SIMULATION// Problem #228
// Implementation here// Summary Ranges - SIMULATION// Problem #228
// Implementation hereApproach 2: Two-Pointer
Section titled “Approach 2: Two-Pointer”Maintain explicit left and right pointers. The right pointer advances; when a gap is detected, both pointers define the current range.
Step-by-step Example
Section titled “Step-by-step Example”Input: nums = [0, 2, 3, 4, 6, 8, 9]
| Step | left | right | nums[left] | nums[right] | Check | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 0 | 0 | 0 | Next (2) != 1 | Save “0”, left=1 |
| 2 | 1 | 1 | 2 | 2 | Next (3) == 3 | Continue |
| 3 | 1 | 2 | 2 | 3 | Next (4) == 4 | Continue |
| 4 | 1 | 3 | 2 | 4 | Next (6) != 5 | Save “2->4”, left=4 |
| 5 | 4 | 4 | 6 | 6 | Next (8) != 7 | Save “6”, left=5 |
| 6 | 5 | 5 | 8 | 8 | Next (9) == 9 | Continue |
| 7 | 5 | 6 | 8 | 9 | End | Save “8->9” |
Pseudocode
Section titled “Pseudocode”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 resultSolution Code
Section titled “Solution Code”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"]// Summary Ranges - POINTERS// Problem #228
// Implementation here// Summary Ranges - POINTERS// Problem #228
// Implementation here// Summary Ranges - POINTERS// Problem #228
// Implementation here// Summary Ranges - POINTERS// Problem #228
// Implementation here// Summary Ranges - POINTERS// Problem #228
// Implementation hereApproach 3: Optimized Two-Pointer
Section titled “Approach 3: Optimized Two-Pointer”A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.
Pseudocode
Section titled “Pseudocode”function approach3(): // Implementation approach goes hereSolution Code
Section titled “Solution Code”"""Solution for Summary Ranges"""
def solve(): """Implementation for approach 3 of Summary Ranges""" pass
if __name__ == "__main__": print("Solution ready")#include <bits/stdc++.h>using namespace std;
// Solution for Summary Ranges// Approach 3: Implementation
int main() {{ // Main implementation goes here return 0;}}/** * Solution for Summary Ranges * Approach 3 */public class SummaryRangesOptimized {{
public static void main(String[] args) {{ // Implementation goes here }}}}/** * Solution for Summary Ranges * Approach 3 */
function solve() {{ // Implementation goes here}}
module.exports = solve;/// Solution for Summary Ranges/// Approach 3
fn main() {{ println!("Solution implementation");}}package main
import "fmt"
// Solution for Summary Ranges// Approach 3
func main() {{ fmt.Println("Solution implementation")}}