Missing Ranges - Problem
Missing Ranges is a classic interval problem that tests your ability to identify gaps in data.

You're given a sorted unique integer array nums and an inclusive range [lower, upper]. All elements in nums are guaranteed to be within this range. Your task is to find all the missing numbers and return them as the shortest possible list of ranges.

For example, if you have nums = [0, 1, 3, 50, 75] and range [0, 99], the missing numbers are 2, 4-49, 51-74, and 76-99. You need to represent single missing numbers as strings like "2" and ranges as "4->49".

Goal: Return a list of range strings that cover all missing numbers with no overlaps or redundancy.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [0, 1, 3, 50, 75], lower = 0, upper = 99
โ€บ Output: ["2", "4->49", "51->74", "76->99"]
๐Ÿ’ก Note: Missing numbers: 2 (single), 4-49 (range), 51-74 (range), 76-99 (range). Each missing number or consecutive group is represented as a range string.
example_2.py โ€” Empty Array
$ Input: nums = [], lower = 1, upper = 1
โ€บ Output: ["1"]
๐Ÿ’ก Note: When nums is empty, the entire range [lower, upper] is missing. Since lower equals upper, we have a single missing number.
example_3.py โ€” No Missing Numbers
$ Input: nums = [-1], lower = -1, upper = -1
โ€บ Output: []
๐Ÿ’ก Note: The array contains the only number in the range [-1, -1], so there are no missing numbers to report.

Constraints

  • -109 โ‰ค lower โ‰ค upper โ‰ค 109
  • 0 โ‰ค nums.length โ‰ค 100
  • lower โ‰ค nums[i] โ‰ค upper
  • All values of nums are unique and sorted in ascending order

Visualization

Tap to expand
๐Ÿจ Hotel Room ManagementHotel Range: Rooms 0-99 | Booked: [0, 1, 3, 50, 75]Find: Available room ranges for new guestsFloor Plan View:0123...50...7576-99๐Ÿ”ด Booked Room๐ŸŸข Available Room/RangeAlgorithm Steps:1. Check before room 0: None2. Gap 1โ†’3: Room 2 available3. Gap 3โ†’50: Rooms 4-49 available4. Gap 50โ†’75: Rooms 51-74 available5. After room 75: Rooms 76-99 availableAvailable Rooms Report: ["2", "4->49", "51->74", "76->99"]โœ… Single pass through bookings | โšก O(n) time | ๐Ÿ’พ O(1) space
Understanding the Visualization
1
Check Lobby Area
Are there available rooms before the first booked room?
2
Walk Through Floors
Walk past each booked room and check for gaps to the next booking
3
Check Top Floors
Are there available rooms after the last booked room?
4
Generate Report
Format available rooms as ranges for the guest services team
Key Takeaway
๐ŸŽฏ Key Insight: By walking through the sorted bookings once and checking gaps, we efficiently find all available ranges without examining every room number.
Asked in
Google 42 Meta 38 Amazon 29 Microsoft 25
78.2K Views
Medium-High Frequency
~18 min Avg. Time
1.8K 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