💡 This approach improves efficiency by scanning the array once and tracking the start of each range, avoiding nested loops.
Intuition
Keep track of the start of the current range and extend it while numbers are consecutive; when a break is found, record the range and start a new one.
Algorithm
- Initialize an empty list for ranges and set start to the first number.
- Iterate through the array from the second element onward.
- If current number is not consecutive to previous, close the previous range and start a new one.
- After iteration, add the last range to the result.
💡 This linear scan is easier to implement and efficient, but requires careful tracking of range boundaries.
from typing import List
def summaryRanges(nums: List[int]) -> List[str]:
if not nums:
return []
ranges = []
start = nums[0]
for i in range(1, len(nums)):
if nums[i] != nums[i-1] + 1:
end = nums[i-1]
if start == end:
ranges.append(str(start))
else:
ranges.append(f"{start}->{end}")
start = nums[i]
# Add the last range
end = nums[-1]
if start == end:
ranges.append(str(start))
else:
ranges.append(f"{start}->{end}")
return ranges
# Example usage
if __name__ == "__main__":
print(summaryRanges([0,1,2,4,5,7])) # ['0->2', '4->5', '7']
Line Notes
if not nums:Handle empty input edge case to avoid errors
ranges = []Initialize list to store final ranges
start = nums[0]Set start of first range
for i in range(1, len(nums)):Iterate from second element to end
if nums[i] != nums[i-1] + 1:Detect break in consecutive sequence
end = nums[i-1]Mark end of current range before break
if start == end:Check if range is a single number
ranges.append(str(start))Add single number as string
ranges.append(f"{start}->{end}")Add range string for multiple numbers
start = nums[i]Start new range at current number
end = nums[-1]After loop, mark end of last range
return rangesReturn list of range strings
import java.util.*;
public class SummaryRanges {
public static List<String> summaryRanges(int[] nums) {
List<String> ranges = new ArrayList<>();
if (nums.length == 0) return ranges;
int start = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1] + 1) {
int end = nums[i - 1];
if (start == end) {
ranges.add(String.valueOf(start));
} else {
ranges.add(start + "->" + end);
}
start = nums[i];
}
}
int end = nums[nums.length - 1];
if (start == end) {
ranges.add(String.valueOf(start));
} else {
ranges.add(start + "->" + end);
}
return ranges;
}
public static void main(String[] args) {
int[] nums = {0,1,2,4,5,7};
System.out.println(summaryRanges(nums)); // ["0->2", "4->5", "7"]
}
}
Line Notes
if (nums.length == 0) return ranges;Handle empty input to avoid errors
List<String> ranges = new ArrayList<>();Initialize list to store ranges
int start = nums[0];Set start of first range
for (int i = 1; i < nums.length; i++) {Iterate from second element
if (nums[i] != nums[i - 1] + 1) {Detect break in consecutive sequence
int end = nums[i - 1];Mark end of current range
if (start == end) {Check if single number range
ranges.add(String.valueOf(start));Add single number as string
ranges.add(start + "->" + end);Add range string for multiple numbers
start = nums[i];Start new range at current number
int end = nums[nums.length - 1];Mark end of last range after loop
return ranges;Return list of ranges
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ranges;
if (nums.empty()) return ranges;
int start = nums[0];
for (int i = 1; i < nums.size(); i++) {
if (nums[i] != nums[i - 1] + 1) {
int end = nums[i - 1];
if (start == end) {
ranges.push_back(to_string(start));
} else {
ranges.push_back(to_string(start) + "->" + to_string(end));
}
start = nums[i];
}
}
int end = nums.back();
if (start == end) {
ranges.push_back(to_string(start));
} else {
ranges.push_back(to_string(start) + "->" + to_string(end));
}
return ranges;
}
int main() {
vector<int> nums = {0,1,2,4,5,7};
vector<string> res = summaryRanges(nums);
for (auto &s : res) cout << s << " ";
cout << endl;
return 0;
}
Line Notes
if (nums.empty()) return ranges;Handle empty input to avoid errors
vector<string> ranges;Initialize vector to store ranges
int start = nums[0];Set start of first range
for (int i = 1; i < nums.size(); i++) {Iterate from second element
if (nums[i] != nums[i - 1] + 1) {Detect break in consecutive sequence
int end = nums[i - 1];Mark end of current range
if (start == end) {Check if single number range
ranges.push_back(to_string(start));Add single number as string
ranges.push_back(to_string(start) + "->" + to_string(end));Add range string for multiple numbers
start = nums[i];Start new range at current number
int end = nums.back();Mark end of last range after loop
return ranges;Return vector of ranges
function summaryRanges(nums) {
if (nums.length === 0) return [];
const ranges = [];
let start = nums[0];
for (let i = 1; i < nums.length; i++) {
if (nums[i] !== nums[i - 1] + 1) {
const end = nums[i - 1];
if (start === end) {
ranges.push(start.toString());
} else {
ranges.push(`${start}->${end}`);
}
start = nums[i];
}
}
const end = nums[nums.length - 1];
if (start === end) {
ranges.push(start.toString());
} else {
ranges.push(`${start}->${end}`);
}
return ranges;
}
// Example usage
console.log(summaryRanges([0,1,2,4,5,7])); // ['0->2', '4->5', '7']
Line Notes
if (nums.length === 0) return [];Handle empty input to avoid errors
const ranges = [];Initialize array to hold range strings
let start = nums[0];Set start of first range
for (let i = 1; i < nums.length; i++) {Iterate from second element
if (nums[i] !== nums[i - 1] + 1) {Detect break in consecutive sequence
const end = nums[i - 1];Mark end of current range
if (start === end) {Check if single number range
ranges.push(start.toString());Add single number as string
ranges.push(`${start}->${end}`);Add range string for multiple numbers
start = nums[i];Start new range at current number
const end = nums[nums.length - 1];Mark end of last range after loop
return ranges;Return array of ranges
Single pass through the array, constant work per element, plus output storage.
💡 For n=1000, this means roughly 1000 operations, which is efficient for large inputs.
Interview Verdict: Accepted and efficient
This is the standard approach to implement in interviews for this problem.