Kth Missing Positive Number — LeetCode 1539 Python Solution

EasyArrayBinary Search
Problem
#1539
Reading time
2 min

The problem

Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Return the kth positive integer that is missing from this array.

Example

Input
arr = [2,3,4,7,11], k = 5
Output
9
Explanation
The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.

Python solution

Python
class Solution:
    def findKthPositive(self, arr: List[int], k: int) -> int:
        if arr[0] > k:
            return k
        left, right = 0, len(arr)
        while left < right:
            mid = (left + right) >> 1
            if arr[mid] - mid - 1 >= k:
                right = mid
            else:
                left = mid + 1
        return arr[left - 1] + k - (arr[left - 1] - (left - 1) - 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 1539. Kth Missing Positive Number 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 1539. Kth Missing Positive Number?
LeetCode 1539. Kth Missing Positive Number is rated Easy on LeetCode.
What topics does LeetCode 1539. Kth Missing Positive Number cover?
LeetCode 1539. Kth Missing Positive Number is tagged Array and Binary Search on LeetCode.

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