#228
Easy Algorithms Summary ranges
Array
53.9% acceptance
Jan 12, 2026
4507
2379
You are given a sorted unique integer array nums.
A range [a,b] is the set of all integers from a to b (inclusive).
Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.
Each range [a,b] in the list should be output as:
"a->b" if a != b
"a" if a == b
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn summary_ranges(nums: Vec<i32>) -> Vec<String> {
if nums.is_empty() { return vec![]; }
let mut result = Vec::new();
let mut start = nums[0];
for i in 1..=nums.len() {
if i == nums.len() || nums[i] != nums[i - 1] + 1 {
if start == nums[i - 1] {
result.push(start.to_string());
} else {
result.push(format!("{}->{}" , start, nums[i - 1]));
}
if i < nums.len() {
start = nums[i];
}
}
}
result
}
}