Missing Element in Sorted Array — LeetCode 1060 Python Solution

MediumLeetCode PremiumArrayBinary Search
Problem
#1060
Reading time
3 min

The problem

Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array.

Example

Input
nums = [4,7,9,10], k = 1
Output
5
Explanation
The first missing number is 5.

Python solution

Python
class Solution:
    def missingElement(self, nums: List[int], k: int) -> int:
        def missing(i: int) -> int:
            return nums[i] - nums[0] - i

        n = len(nums)
        if k > missing(n - 1):
            return nums[n - 1] + k - missing(n - 1)
        l, r = 0, n - 1
        while l < r:
            mid = (l + r) >> 1
            if missing(mid) >= k:
                r = mid
            else:
                l = mid + 1
        return nums[l - 1] + k - missing(l - 1)

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1060. Missing Element in Sorted Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1060. Missing Element in Sorted Array?
LeetCode 1060. Missing Element in Sorted Array is rated Medium on LeetCode.
What topics does LeetCode 1060. Missing Element in Sorted Array cover?
LeetCode 1060. Missing Element in Sorted Array is tagged Array and Binary Search on LeetCode.
Is LeetCode 1060. Missing Element in Sorted Array a premium problem?
Yes. LeetCode 1060. Missing Element in Sorted Array 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.

Get Stealth Interview