EasyNo. 0163LeetCode Premium

Missing Ranges — LeetCode 163 Python Solution

Topics
Array
Reading time
3 min

The 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.

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:

Python solution

PythonSolution
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

Time
O(n)where n is the length of the array nums
Space · auxiliary
O(1)

Related problems

Related problems
No.ProblemDifficulty
0057Insert IntervalMedium
0228Summary RangesEasy
0485Max Consecutive OnesEasy
0665Non-decreasing ArrayMedium
0674Longest Continuous Increasing SubsequenceEasy
0699Falling SquaresHard

Frequently asked questions

How hard is LeetCode 163. Missing Ranges?

LeetCode 163. Missing Ranges is rated Easy on LeetCode.

What is the time complexity of LeetCode 163. Missing Ranges?

The Python solution on this page runs in O(n), where n is the length of the array nums.

What is the space complexity of LeetCode 163. Missing Ranges?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 163. Missing Ranges cover?

LeetCode 163. Missing Ranges is tagged Array on LeetCode.

Is LeetCode 163. Missing Ranges a premium problem?

Yes. LeetCode 163. Missing Ranges is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.