πDay 8. Kth Missing Positive Number in a Sorted Array π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given a sorted array of distinct positive integers arr[] and an integer k, find the kth positive number that is missing from the array.
π Example Walkthrough:
Input:
arr = [2, 3, 4, 7, 11]
k = 5Output:
9Explanation:
The missing numbers are 1, 5, 6, 8, 9, 10, .... The 5th missing number is 9.
Input:
arr = [3, 5, 9, 10, 11, 12]
k = 2Output:
2Explanation:
The missing numbers are 1, 2, 4, 6, 7.... The 2nd missing number is 2.
Constraints:
$
1 <= arr.size() <= 10^5$$
1 <= k <= 10^5$$
1 <= arr[i]<= 10^6$
π― My Approach:
Binary Search
Key Observations:
For an index
iinarr, the number of missing positive integers up toarr[i]is given by: $[ \text{Missing Numbers} = arr[i] - (i + 1) $]If this count is less than
k, thekth missing number lies afterarr[i]. Otherwise, it lies beforearr[i].
Steps:
Use binary search over the array to find the smallest index
isuch that the count of missing numbers is at leastk.Once located, calculate the
kth missing number using: $[ \text{Result} = \text{Index} + k ]$
Edge Case:
If all missing numbers are after the largest element in
arr, return: $[ arr[-1] + (k - \text{Missing Numbers till end}) ]$
π Time and Auxiliary Space Complexity
Expected Time Complexity:
$[ O(log n) $]
where n is the size of the array, as binary search is used to locate the position.
Expected Auxiliary Space Complexity: $[ O(1) $] since no additional data structures are used apart from a few variables.
π Solution Code
Code (C)
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, please visit my LinkedIn:- Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
β Star this repository if you find it helpful or intriguing! β
πVisitor Count
Last updated