Missing Ranges - Problem

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.

Each range [a,b] in the list should be output as:

  • "a->b" if a != b
  • "a" if a == b

Input & Output

Example 1 — Basic Missing Ranges
$ Input: nums = [0,1,3,50,75], lower = 0, upper = 99
Output: ["2","4->49","51->74","76->99"]
💡 Note: Missing ranges: 2 (single number), 4-49 (range), 51-74 (range), and 76-99 (range)
Example 2 — Single Missing Number
$ Input: nums = [1,3], lower = 1, upper = 3
Output: ["2"]
💡 Note: Only number 2 is missing from range [1,3]
Example 3 — Empty Array
$ Input: nums = [], lower = 1, upper = 1
Output: ["1"]
💡 Note: Array is empty, so entire range [1,1] is missing

Constraints

  • -109 ≤ lower ≤ upper ≤ 109
  • 0 ≤ nums.length ≤ 100
  • lower ≤ nums[i] ≤ upper
  • All values in nums are unique

Visualization

Tap to expand
Missing Ranges: Find Gaps in [0,99]Range: [0,99]0135075nums24-4951-7476-99Missing rangesFormat: single numbers as "2", ranges as "4->49"Output: ["2", "4->49", "51->74", "76->99"]
Understanding the Visualization
1
Input
Sorted array nums and range [lower, upper]
2
Process
Find gaps between consecutive elements
3
Output
Format missing ranges as strings
Key Takeaway
🎯 Key Insight: Instead of checking every number in the range, examine gaps between consecutive existing numbers for optimal O(n) solution
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 22
28.5K Views
Medium Frequency
~15 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen