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 - One Pass Gap Detection INPUT nums array (sorted, unique): 0 1 3 50 75 idx 0 idx 1 idx 2 idx 3 idx 4 Range: [lower, upper] [0, 99] Number Line View: 0 1 3 50 75 99 gap gap gap gap nums = [0,1,3,50,75] lower=0, upper=99 ALGORITHM STEPS 1 Initialize prev = lower - 1 prev = -1 (track last seen) 2 Iterate through nums For each num, check gap 3 Detect gaps If num - prev > 1: add range 4 Check final gap Compare last num to upper Gap Detection Process: prev num gap? range -1 0 no - 0 1 no - 1 3 YES "2" 3 50 YES "4-->49" 50 75 YES "51-->74" 75 100 YES "76-->99" (upper+1) FINAL RESULT Missing Ranges Found: "2" Single value: 2 "4-->49" Range: 4 to 49 (46 nums) "51-->74" Range: 51 to 74 (24 nums) "76-->99" Range: 76 to 99 (24 nums) Output: ["2","4-->49","51-->74","76-->99"] OK - All gaps covered! Key Insight: The one-pass approach uses a "previous" pointer starting at lower-1. For each number in nums, if the gap between prev and current num is greater than 1, we have missing numbers in [prev+1, num-1]. After the loop, check if last num is less than upper to capture the final range. Time: O(n), Space: O(1). TutorialsPoint - Missing Ranges | One Pass Gap Detection
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