Kth Missing Positive Number - Problem
Find the Kth Missing Positive Integer
You're given a sorted array of positive integers with some numbers missing from the sequence. Your task is to find the kth missing positive integer that should have been in the natural sequence but isn't present in the array.
For example, if the array is
Goal: Return the kth missing positive integer efficiently.
Input: A sorted array of positive integers and an integer k
Output: The kth missing positive integer
You're given a sorted array of positive integers with some numbers missing from the sequence. Your task is to find the kth missing positive integer that should have been in the natural sequence but isn't present in the array.
For example, if the array is
[2, 3, 4, 7, 11], the missing positive integers are 1, 5, 6, 8, 9, 10, 12, ...Goal: Return the kth missing positive integer efficiently.
Input: A sorted array of positive integers and an integer k
Output: The kth missing positive integer
Input & Output
example_1.py โ Basic Case
$
Input:
arr = [2,3,4,7,11], k = 5
โบ
Output:
9
๐ก Note:
The missing positive integers are [1,5,6,8,9,10,12,...]. The 5th missing positive integer is 9.
example_2.py โ Small Array
$
Input:
arr = [1,2,3,4], k = 2
โบ
Output:
6
๐ก Note:
The missing positive integers are [5,6,7,8,...]. The 2nd missing positive integer is 6.
example_3.py โ Array Starts High
$
Input:
arr = [10,20,30], k = 1
โบ
Output:
1
๐ก Note:
The missing positive integers are [1,2,3,4,5,6,7,8,9,11,...]. The 1st missing positive integer is 1.
Constraints
- 1 โค arr.length โค 1000
- 1 โค arr[i] โค 1000
- 1 โค k โค 1000
- arr is sorted in strictly increasing order
Visualization
Tap to expand
Understanding the Visualization
1
Identify Reserved Seats
The array represents VIP-reserved seats [2,3,4,7,11]
2
Count Available Seats
For each reserved seat, calculate how many regular seats are available before it
3
Binary Search
Use binary search to quickly find which section contains the kth available seat
4
Calculate Final Seat
Once we know the section, calculate the exact seat number
Key Takeaway
๐ฏ Key Insight: By calculating how many seats are missing before each VIP reservation, we can use binary search to jump directly to the section containing our answer, achieving O(log n) time complexity!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code