#163
Easy Algorithms Missing ranges
Array
35.5% acceptance
Apr 1, 2026
1182
3021
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are within the inclusive range.
A number x is considered missing if x is in the range [lower, upper] and x is not in nums.
Return the shortest sorted list of ranges that exactly covers all the missing numbers. That is, no element of nums is included in any of the ranges, and each missing number is covered by one of the ranges.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn find_missing_ranges(nums: Vec<i32>, lower: i32, upper: i32) -> Vec<Vec<i32>> {
let mut result = Vec::new();
let mut prev = lower as i64 - 1;
let nums_ext: Vec<i64> = nums.iter().map(|&x| x as i64).chain(std::iter::once(upper as i64 + 1)).collect();
for &num in &nums_ext {
if num - prev >= 2 {
result.push(vec![(prev + 1) as i32, (num - 1) as i32]);
}
prev = num;
}
result
}
}