Leetcode #163: Missing Ranges
In this guide, we solve Leetcode #163 Missing Ranges in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: Yes
- Tags: Array
Intuition
The constraints allow a direct scan that keeps only the essential state.
By translating the requirements into a clean loop, the logic stays easy to reason about.
Approach
Iterate through the data once, updating the state needed to compute the answer.
Return the final state after the traversal is complete.
Steps:
- Parse the input.
- Iterate and update state.
- Return the computed answer.
Example
Input: nums = [0,1,3,50,75], lower = 0, upper = 99
Output: [[2,2],[4,49],[51,74],[76,99]]
Explanation: The ranges are:
[2,2]
[4,49]
[51,74]
[76,99]
Python Solution
class Solution:
def findMissingRanges(
self, nums: List[int], lower: int, upper: int
) -> List[List[int]]:
n = len(nums)
if n == 0:
return [[lower, upper]]
ans = []
if nums[0] > lower:
ans.append([lower, nums[0] - 1])
for a, b in pairwise(nums):
if b - a > 1:
ans.append([a + 1, b - 1])
if nums[-1] < upper:
ans.append([nums[-1] + 1, upper])
return ans
Complexity
The time complexity is , where is the length of the array . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.