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 1:
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.
Example 2:
Input: arr = [1,2,3,4], k = 2 Output: 6 Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
Constraints:
1 <= arr.length <= 10001 <= arr[i] <= 10001 <= k <= 1000arr[i] < arr[j] for 1 <= i < j <= arr.length
Follow up:
Could you solve this problem in less than O(n) complexity?
This approach involves iterating through the array and maintaining a counter for missing positive integers. We start with the first positive number, which is 1, and determine if it is missing by comparing it to the current element in the array. If the number is missing, we decrement our k value. When k reaches zero, we have found our k-th missing number.
This C solution uses a simple iteration where it keeps track of what the next missing number should be while iterating over the array. It compares the current number to the next expected missing number. If the expected number is equal to the array number, it means the number is not missing, so it moves to the next array element. Otherwise, it increases the missing count and checks if it matches k.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n + k), where n is the length of the array. Space Complexity: O(1), as we are using constant extra space.
By using binary search, a more efficient solution can be developed that reduces unnecessary checks. The key observation is that the number of missing integers before arr[i] can be calculated as arr[i] - (i + 1), which helps in deducing the position of the k-th missing number without iterating through every integer.
This implementation uses binary search to efficiently find the k-th missing positive number. The search focuses on a "missing" variable that tells how many numbers are missing up to the mid-point in the array.
C++
Java
Python
C#
JavaScript
Time Complexity: O(log n), Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Iterative Approach | Time Complexity: O(n + k), where n is the length of the array. Space Complexity: O(1), as we are using constant extra space. |
| Binary Search Optimization | Time Complexity: O(log n), Space Complexity: O(1). |
BS-16. Kth Missing Positive Number | Maths + Binary Search • take U forward • 211,898 views views
Watch 9 more video solutions →Practice Kth Missing Positive Number with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor