Kth Missing Positive Number — LeetCode 1539 Python Solution
- Problem
- #1539
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(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.