Kth Missing Positive Number
LeetCode 1539 · Easy · solution, intuition & step-by-step walkthrough
missing(i) = arr[i] − (i + 1); answer = low + k.
This is how I solved Kth Missing Positive Number (LeetCode 1539), an easy problem from the Math / Missing Numbers pattern. Below: the intuition, the approach step by step, my accepted Python code and the 2 versions I wrote on the way, animated test cases and a line-by-line debugger.
Intuition
At index i, the count of missing numbers before arr[i] is arr[i] − (i + 1). Binary search the last index where fewer than k numbers are missing; the answer is then low + k.
Approach
- 1
Linear version: every array value ≤ k pushes the answer up by one.
- 2
Binary search on missing(mid) < k.
- 3
After the loop, return low + k.
How I solved it · from first idea to final
Bump k past each present number.
Search on the missing count.
Linear shiftPythonO(n) time
class Solution:
def findKthPositive(self, nums: List[int], k: int) -> int:
for num in nums:
if num>k:
break
else:
k=k+1
return kBinary searchPythonO(log n) time
class Solution:
def findKthPositive(self, nums: List[int], k: int) -> int:
low=0
high = len(nums)-1
while low<=high:
mid = (low+high)//2
missing = nums[mid]-(mid+1)
if missing<k:
low = mid+1
else:
high = mid-1
return low+kKth Missing Positive Number — FAQ
What is the intuition behind Kth Missing Positive Number?
At index i, the count of missing numbers before arr[i] is arr[i] − (i + 1). Binary search the last index where fewer than k numbers are missing; the answer is then low + k.
How do you solve Kth Missing Positive Number (LeetCode 1539)?
1. Linear version: every array value ≤ k pushes the answer up by one. 2. Binary search on missing(mid) < k. 3. After the loop, return low + k.
What is the time and space complexity of Kth Missing Positive Number?
Time: O(log n). Space: O(1). (Accepted approach: Binary search.)
What are common mistakes in Kth Missing Positive Number?
The answer may be beyond the last element.
Is there more than one way to solve Kth Missing Positive Number?
Linear shift (O(n) time): Bump k past each present number. Binary search (O(log n) time): Search on the missing count.