#1539

Kth Missing Positive Number

Easy
ArrayBinary SearchBinary SearchArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

The optimal solution uses a binary search-like approach to efficiently find the k-th missing number by leveraging the sorted nature of the array. We can calculate how many numbers are missing up to each point in the array.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize two pointers, left and right, to 0 and the length of the array respectively.
  2. 2Step 2: While left is less than right, calculate the mid-point and determine how many numbers are missing up to that point.
  3. 3Step 3: If the number of missing integers is less than k, move the left pointer to mid + 1.
  4. 4Step 4: If the number of missing integers is greater than or equal to k, move the right pointer to mid.
  5. 5Step 5: After the loop, return the result based on the left pointer's position.
solution.py15 lines
1# Full working Python code
2
3def findKthPositive(arr, k):
4    left, right = 0, len(arr)
5    while left < right:
6        mid = (left + right) // 2
7        missing = arr[mid] - (mid + 1)
8        if missing < k:
9            left = mid + 1
10        else:
11            right = mid
12    return left + k
13
14# Example usage
15print(findKthPositive([2,3,4,7,11], 5))  # Output: 9

Complexity note: This complexity is achieved because we are using a binary search approach, which reduces the number of checks we need to perform significantly compared to the brute force method.

  • 1The problem can be solved by leveraging the sorted nature of the input array.
  • 2Using a binary search approach allows us to find the k-th missing number efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.