Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find kth missing positive number in an array in Python
Suppose we have an array called nums with positive sorted strictly increasing values, and also have an integer k. We have to find the kth positive integer that is missing from this array.
So, if the input is like nums = [1,2,4,8,12], k = 6, then the output will be 10 because the missing numbers are [3,5,6,7,9,10,11], here the 6th term is 10.
Approach
To solve this, we will follow these steps ?
Convert the array to a set for O(1) lookup time
Initialize a counter for missing numbers and start checking from 1
For each positive integer, check if it's missing from the set
When we find the kth missing number, return it
Example
Let us see the following implementation to get better understanding ?
def solve(nums, k):
nums = set(nums)
count = 0
num = 1
while count < k:
if num not in nums:
count += 1
if count == k:
return num
num += 1
return num
nums = [1, 2, 4, 8, 12]
k = 6
result = solve(nums, k)
print(f"The {k}th missing positive number is: {result}")
The output of the above code is ?
The 6th missing positive number is: 10
Step-by-Step Execution
Let's trace through the algorithm with our example ?
def solve_with_trace(nums, k):
nums_set = set(nums)
count = 0
num = 1
print(f"Original array: {sorted(nums)}")
print(f"Looking for {k}th missing number")
print("Missing numbers found:")
while count < k:
if num not in nums_set:
count += 1
print(f"{count}: {num}")
if count == k:
return num
num += 1
return num
nums = [1, 2, 4, 8, 12]
k = 6
result = solve_with_trace(nums, k)
print(f"\nAnswer: {result}")
The output shows the process ?
Original array: [1, 2, 4, 8, 12] Looking for 6th missing number Missing numbers found: 1: 3 2: 5 3: 6 4: 7 5: 9 6: 10 Answer: 10
Alternative Approach Using Binary Search
For larger arrays, we can use binary search for better efficiency ?
def find_kth_missing_binary_search(nums, k):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
missing_count = nums[mid] - (mid + 1)
if missing_count < k:
left = mid + 1
else:
right = mid - 1
return left + k
nums = [1, 2, 4, 8, 12]
k = 6
result = find_kth_missing_binary_search(nums, k)
print(f"Using binary search: {result}")
Using binary search: 10
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Set-based iteration | O(n + k) | O(n) | Small arrays, easy to understand |
| Binary search | O(log n) | O(1) | Large sorted arrays |
Conclusion
The set-based approach is intuitive and works well for most cases. For large sorted arrays, the binary search method offers better time complexity by calculating missing numbers mathematically rather than iterating through each positive integer.
