NeetCode #829LC-163EasyIntervalsNC Algo100
← Back to All Problems#829 · #163 · Missing Ranges(缺失的区间)
📌 Problem Statement & Constraints
You are given a sorted integer array
nums with distinct values and inclusive bounds lower and upper. Return the list of missing ranges in [lower, upper] as [start, end] pairs. Constraints: -10^9 <= lower <= upper <= 10^9, -10^9 <= nums[i] <= 10^9, nums is sorted and distinct.💡 Core Algorithmic Approaches
- Think of a virtual cursor
prevthat starts just beforelower(atlower - 1). - Walk through
numsplus a sentinelupper + 1; for each valuev, the gap(prev, v)is missing ifv - prev > 1. - Emit
[prev + 1, v - 1]for each non-empty gap. - The sentinel handles the tail so no separate case is needed.
💻 Benchmark Python3 Implementation
class Solution:
def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[List[int]]:
res = []
prev = lower - 1 # cursor just before the range
for v in nums + [upper + 1]: # sentinel closes the tail
if v - prev > 1:
res.append([prev + 1, v - 1])
prev = v
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass with O(1) work per element.
💾 Space Complexity
O(n) for the output list.
⚠️ Interview Pitfalls & Follow-ups
- Using
v - prev > 0: a single missing value forms a range of length one, so the gap must be strictly greater than 1. - Forgetting the tail: after the last array element there may be a gap up to
upper, handled by theupper + 1sentinel. - Emitting empty ranges: when
v == prev + 1there is no gap, so the guard is essential. - Underflow on
lower - 1: with the stated bounds (about10^9) this is safe in Python, but in fixed-width languages the sentinel must be chosen carefully.