Bird
Raised Fist0
Interview Prepmodified-binary-searcheasyAmazonGoogle

Find Kth Positive Missing Number

Choose your preparation mode4 modes available
🎯
Find Kth Positive Missing Number
easyBINARY_SEARCHAmazonGoogle

Imagine you have a sorted list of positive integers representing IDs assigned to users, but some IDs are missing. You want to find the Kth missing ID to assign it next.

💡 This problem is about finding missing elements in a sorted sequence. Beginners often struggle because they try to scan linearly or guess the missing numbers instead of using the sorted property to efficiently find the answer.
📋
Problem Statement

Given a sorted array arr of positive integers and an integer k, return the kth positive integer that is missing from this array.

1 ≤ arr.length ≤ 10^51 ≤ arr[i] ≤ 10^71 ≤ k ≤ 10^8arr is strictly increasing
💡
Example
Input"arr = [2,3,4,7,11], k = 5"
Output9

The missing positive integers are [1,5,6,8,9,10,...]. The 5th missing is 9.

Input"arr = [1,2,3,4], k = 2"
Output6

Missing positive integers are [5,6,7,...]. The 2nd missing is 6.

  • k is smaller than the first missing number → output is less than arr[0]
  • k is larger than all missing numbers within arr range → output beyond arr[-1]
  • arr contains consecutive numbers with no missing in between → missing numbers start after arr[-1]
  • arr has only one element → missing numbers start before or after that element
⚠️
Common Mistakes
Not accounting for missing numbers before the first element

Incorrect answer when kth missing is less than arr[0]

✅ Check if kth missing is less than arr[0] and return k directly if so

Off-by-one errors in binary search boundaries

Infinite loops or wrong index found

✅ Carefully update left and right pointers and test boundary conditions

Miscomputing missing count as arr[mid] - mid instead of arr[mid] - (mid + 1)

Wrong missing count leads to incorrect binary search decisions

✅ Remember missing count before index mid is arr[mid] - (mid + 1)

Not handling case when kth missing is beyond last element

Code returns wrong number or crashes

✅ Calculate total missing before last element and handle k accordingly

🧠
Brute Force (Linear Scan)
💡 This approach exists to build intuition by directly simulating the missing numbers. It is simple but inefficient, helping beginners understand the problem before optimizing.

Intuition

Check every positive integer starting from 1, count how many are missing from the array until we reach the kth missing.

Algorithm

  1. Initialize a pointer i for the array and a counter for missing numbers.
  2. Iterate from 1 upwards, checking if the current number matches arr[i].
  3. If it matches, move i forward; else increment missing count.
  4. When missing count reaches k, return the current number.
💡 This algorithm is straightforward but inefficient because it checks every number one by one, which is easy to understand but slow for large inputs.
</>
Code
def findKthPositive(arr, k):
    missing_count = 0
    current = 1
    i = 0
    n = len(arr)
    while True:
        if i < n and arr[i] == current:
            i += 1
        else:
            missing_count += 1
            if missing_count == k:
                return current
        current += 1

# Driver code
if __name__ == '__main__':
    print(findKthPositive([2,3,4,7,11], 5))  # Output: 9
Line Notes
missing_count = 0Initialize count of missing numbers found so far
current = 1Start checking from the smallest positive integer
if i < n and arr[i] == currentCheck if current number is present in array
missing_count += 1Increment missing count when current is not in array
if missing_count == kReturn current when kth missing number is found
public class Solution {
    public static int findKthPositive(int[] arr, int k) {
        int missingCount = 0, current = 1, i = 0, n = arr.length;
        while (true) {
            if (i < n && arr[i] == current) {
                i++;
            } else {
                missingCount++;
                if (missingCount == k) {
                    return current;
                }
            }
            current++;
        }
    }

    public static void main(String[] args) {
        System.out.println(findKthPositive(new int[]{2,3,4,7,11}, 5)); // 9
    }
}
Line Notes
int missingCount = 0Initialize missing count to zero
int current = 1Start checking from 1
if (i < n && arr[i] == current)Check if current number is in array
missingCount++Increment missing count if current is missing
if (missingCount == k)Return current when kth missing found
#include <iostream>
#include <vector>
using namespace std;

int findKthPositive(vector<int>& arr, int k) {
    int missingCount = 0, current = 1, i = 0, n = arr.size();
    while (true) {
        if (i < n && arr[i] == current) {
            i++;
        } else {
            missingCount++;
            if (missingCount == k) {
                return current;
            }
        }
        current++;
    }
}

int main() {
    vector<int> arr = {2,3,4,7,11};
    cout << findKthPositive(arr, 5) << endl; // 9
    return 0;
}
Line Notes
int missingCount = 0Initialize count of missing numbers
int current = 1Start from smallest positive integer
if (i < n && arr[i] == current)Check if current is in array
missingCount++Increment missing count if current missing
if (missingCount == k)Return current when kth missing found
function findKthPositive(arr, k) {
    let missingCount = 0, current = 1, i = 0, n = arr.length;
    while (true) {
        if (i < n && arr[i] === current) {
            i++;
        } else {
            missingCount++;
            if (missingCount === k) {
                return current;
            }
        }
        current++;
    }
}

// Test
console.log(findKthPositive([2,3,4,7,11], 5)); // 9
Line Notes
let missingCount = 0Initialize missing count
let current = 1Start checking from 1
if (i < n && arr[i] === current)Check if current number is in array
missingCount++Increment missing count if current missing
if (missingCount === k)Return current when kth missing found
⏱
Complexity
TimeO(k + n)
SpaceO(1)

We potentially iterate up to k missing numbers and scan through the array with pointer i. For large k, this is inefficient.

💡 If k=10^5, this means up to 100,000 iterations, which is slow but still feasible; for larger k, it becomes impractical.
Interview Verdict: TLE for large inputs

This approach is too slow for large inputs but helps understand the problem before optimizing.

🧠
Binary Search on Missing Count
💡 This approach uses binary search to leverage the sorted array and count missing numbers efficiently, improving performance drastically.

Intuition

At any index, the count of missing numbers before that index can be computed. Use binary search to find the smallest index where missing count is at least k.

Algorithm

  1. Define a function to count missing numbers before index mid: arr[mid] - (mid + 1).
  2. Use binary search on indices [0, n-1] to find the smallest index where missing count >= k.
  3. If no such index, kth missing is beyond arr[-1], so return arr[-1] + (k - missing count at end).
  4. Otherwise, calculate kth missing number using arr[left-1] and k.
💡 This algorithm cleverly uses the property that missing count increases monotonically, allowing binary search to find the answer in logarithmic time.
</>
Code
def findKthPositive(arr, k):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        missing = arr[mid] - (mid + 1)
        if missing < k:
            left = mid + 1
        else:
            right = mid - 1
    if right == -1:
        return k
    return arr[right] + (k - (arr[right] - (right + 1)))

# Driver code
if __name__ == '__main__':
    print(findKthPositive([2,3,4,7,11], 5))  # Output: 9
Line Notes
left, right = 0, len(arr) - 1Initialize binary search boundaries
missing = arr[mid] - (mid + 1)Calculate missing count before mid index
if missing < kIf missing count less than k, search right half
else: right = mid - 1Else search left half to find lower bound
if right == -1If no missing before first element, kth missing is k
return arr[right] + (k - (arr[right] - (right + 1)))Calculate kth missing number based on previous element
public class Solution {
    public static int findKthPositive(int[] arr, int k) {
        int left = 0, right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            int missing = arr[mid] - (mid + 1);
            if (missing < k) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        if (right == -1) return k;
        return arr[right] + (k - (arr[right] - (right + 1)));
    }

    public static void main(String[] args) {
        System.out.println(findKthPositive(new int[]{2,3,4,7,11}, 5)); // 9
    }
}
Line Notes
int left = 0, right = arr.length - 1Set binary search boundaries
int missing = arr[mid] - (mid + 1)Compute missing count before mid
if (missing < k)If missing less than k, move right
else { right = mid - 1; }Else move left to find lower bound
if (right == -1) return k;If no missing before first element, return k
return arr[right] + (k - (arr[right] - (right + 1)));Calculate kth missing number
#include <iostream>
#include <vector>
using namespace std;

int findKthPositive(vector<int>& arr, int k) {
    int left = 0, right = arr.size() - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        int missing = arr[mid] - (mid + 1);
        if (missing < k) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    if (right == -1) return k;
    return arr[right] + (k - (arr[right] - (right + 1)));
}

int main() {
    vector<int> arr = {2,3,4,7,11};
    cout << findKthPositive(arr, 5) << endl; // 9
    return 0;
}
Line Notes
int left = 0, right = arr.size() - 1Initialize binary search range
int missing = arr[mid] - (mid + 1)Calculate missing count before mid
if (missing < k)If missing less than k, search right half
else { right = mid - 1; }Else search left half
if (right == -1) return k;If no missing before first element, kth missing is k
return arr[right] + (k - (arr[right] - (right + 1)));Compute kth missing number
function findKthPositive(arr, k) {
    let left = 0, right = arr.length - 1;
    while (left <= right) {
        let mid = Math.floor((left + right) / 2);
        let missing = arr[mid] - (mid + 1);
        if (missing < k) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    if (right === -1) return k;
    return arr[right] + (k - (arr[right] - (right + 1)));
}

// Test
console.log(findKthPositive([2,3,4,7,11], 5)); // 9
Line Notes
let left = 0, right = arr.length - 1Set binary search boundaries
let missing = arr[mid] - (mid + 1)Calculate missing count before mid
if (missing < k)If missing less than k, move right
else { right = mid - 1; }Else move left to find lower bound
if (right === -1) return k;If no missing before first element, return k
return arr[right] + (k - (arr[right] - (right + 1)));Calculate kth missing number
⏱
Complexity
TimeO(log n)
SpaceO(1)

Binary search reduces the search space logarithmically by using missing count property.

💡 For n=10^5, this means about 17 steps, which is very efficient.
Interview Verdict: Accepted

This is the optimal approach for large inputs and is expected in interviews.

🧠
Direct Mathematical Calculation (No Binary Search)
💡 This approach uses the insight that if kth missing is beyond the last element, we can calculate it directly without searching.

Intuition

If total missing numbers within array length is less than k, kth missing is after last element; else use binary search to find position.

Algorithm

  1. Calculate total missing numbers before the last element: arr[-1] - n.
  2. If k is greater than total missing, return arr[-1] + (k - total missing).
  3. Else perform binary search as in Approach 2 to find kth missing inside array.
💡 This approach optimizes by avoiding binary search when kth missing is beyond the array, saving time.
</>
Code
def findKthPositive(arr, k):
    n = len(arr)
    total_missing = arr[-1] - n
    if k > total_missing:
        return arr[-1] + (k - total_missing)
    left, right = 0, n - 1
    while left <= right:
        mid = (left + right) // 2
        missing = arr[mid] - (mid + 1)
        if missing < k:
            left = mid + 1
        else:
            right = mid - 1
    return arr[right] + (k - (arr[right] - (right + 1)))

# Driver code
if __name__ == '__main__':
    print(findKthPositive([2,3,4,7,11], 5))  # Output: 9
Line Notes
total_missing = arr[-1] - nCalculate total missing numbers before last element
if k > total_missingIf kth missing beyond last element, calculate directly
left, right = 0, n - 1Initialize binary search boundaries
missing = arr[mid] - (mid + 1)Calculate missing count before mid
if missing < kAdjust search boundaries based on missing count
return arr[right] + (k - (arr[right] - (right + 1)))Calculate kth missing number inside array
public class Solution {
    public static int findKthPositive(int[] arr, int k) {
        int n = arr.length;
        int totalMissing = arr[n - 1] - n;
        if (k > totalMissing) {
            return arr[n - 1] + (k - totalMissing);
        }
        int left = 0, right = n - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            int missing = arr[mid] - (mid + 1);
            if (missing < k) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return arr[right] + (k - (arr[right] - (right + 1)));
    }

    public static void main(String[] args) {
        System.out.println(findKthPositive(new int[]{2,3,4,7,11}, 5)); // 9
    }
}
Line Notes
int totalMissing = arr[n - 1] - nCalculate total missing numbers before last element
if (k > totalMissing)If kth missing beyond last element, return directly
int left = 0, right = n - 1Initialize binary search boundaries
int missing = arr[mid] - (mid + 1)Calculate missing count before mid
if (missing < k)Adjust binary search boundaries
return arr[right] + (k - (arr[right] - (right + 1)))Calculate kth missing inside array
#include <iostream>
#include <vector>
using namespace std;

int findKthPositive(vector<int>& arr, int k) {
    int n = arr.size();
    int totalMissing = arr[n - 1] - n;
    if (k > totalMissing) {
        return arr[n - 1] + (k - totalMissing);
    }
    int left = 0, right = n - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        int missing = arr[mid] - (mid + 1);
        if (missing < k) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return arr[right] + (k - (arr[right] - (right + 1)));
}

int main() {
    vector<int> arr = {2,3,4,7,11};
    cout << findKthPositive(arr, 5) << endl; // 9
    return 0;
}
Line Notes
int totalMissing = arr[n - 1] - nCalculate total missing numbers before last element
if (k > totalMissing)If kth missing beyond last element, return directly
int left = 0, right = n - 1Initialize binary search boundaries
int missing = arr[mid] - (mid + 1)Calculate missing count before mid
if (missing < k)Adjust binary search boundaries
return arr[right] + (k - (arr[right] - (right + 1)))Calculate kth missing inside array
function findKthPositive(arr, k) {
    const n = arr.length;
    const totalMissing = arr[n - 1] - n;
    if (k > totalMissing) {
        return arr[n - 1] + (k - totalMissing);
    }
    let left = 0, right = n - 1;
    while (left <= right) {
        let mid = Math.floor((left + right) / 2);
        let missing = arr[mid] - (mid + 1);
        if (missing < k) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return arr[right] + (k - (arr[right] - (right + 1)));
}

// Test
console.log(findKthPositive([2,3,4,7,11], 5)); // 9
Line Notes
const totalMissing = arr[n - 1] - nCalculate total missing numbers before last element
if (k > totalMissing)If kth missing beyond last element, return directly
let left = 0, right = n - 1Initialize binary search boundaries
let missing = arr[mid] - (mid + 1)Calculate missing count before mid
if (missing < k)Adjust binary search boundaries
return arr[right] + (k - (arr[right] - (right + 1)))Calculate kth missing inside array
⏱
Complexity
TimeO(log n)
SpaceO(1)

This approach adds a constant time check before binary search, keeping overall complexity logarithmic.

💡 This small optimization can save time when kth missing is beyond the array, common in real inputs.
Interview Verdict: Accepted

This is the most practical approach combining math and binary search, ideal for interviews.

📊
All Approaches - One-Glance Tradeoffs
💡 For interviews, approach 2 or 3 is best to code. Approach 1 is only for explanation.
ApproachTimeSpaceStack RiskReconstructUse In Interview
1. Brute ForceO(k + n)O(1)NoN/AMention only - never code for large inputs
2. Binary Search on Missing CountO(log n)O(1)NoN/AOptimal approach to code in interviews
3. Direct Mathematical Calculation + Binary SearchO(log n)O(1)NoN/ABest practical approach combining math and binary search
💼
Interview Strategy
💡 Use this guide to understand the problem deeply, practice all approaches, and prepare to explain your reasoning clearly in interviews.

How to Present

Step 1: Clarify the problem and constraints with the interviewer.Step 2: Present the brute force approach to show understanding.Step 3: Explain the inefficiency and motivate binary search.Step 4: Implement binary search approach with clear explanation.Step 5: Discuss edge cases and test your code thoroughly.

Time Allocation

Clarify: 2min → Approach: 3min → Code: 10min → Test: 5min. Total ~20min

What the Interviewer Tests

The interviewer tests your problem understanding, ability to optimize using binary search, and correctness on edge cases.

Common Follow-ups

  • What if the array is empty? → The kth missing is k itself.
  • Can you solve without binary search? → Yes, but less efficient.
  • How to handle very large k values? → Use the direct calculation approach.
  • What if array is not sorted? → Sort first or use a different approach.
💡 These follow-ups test your robustness and ability to handle variations or constraints in the problem.
🔍
Pattern Recognition

When to Use

1) Sorted array with missing elements 2) Need to find kth missing 3) Missing count can be computed 4) Monotonic property allows binary search

Signature Phrases

'kth positive integer missing from this array''arr is strictly increasing''find the kth missing number'

NOT This Pattern When

Problems that ask for missing numbers but arrays are unsorted or no monotonic property exist

Similar Problems

Missing Number - simpler missing element problem using XOR or sumFirst Missing Positive - find smallest missing positive integerFind Smallest Missing Number - binary search on missing count

Practice

(1/5)
1. Given the following code for finding a peak element, what is the final output when the input array is [1, 3, 2]?
def findPeakElement(nums):
    def binarySearch(low, high):
        if low == high:
            return low
        mid = (low + high) // 2
        if nums[mid] < nums[mid + 1]:
            return binarySearch(mid + 1, high)
        else:
            return binarySearch(low, mid)
    return binarySearch(0, len(nums) - 1)

print(findPeakElement([1, 3, 2]))
easy
A. None of the above
B. 0
C. 2
D. 1

Solution

  1. Step 1: Trace first call binarySearch(0, 2)

    mid = (0+2)//2 = 1; nums[1]=3, nums[2]=2; since 3 > 2, recurse binarySearch(0,1)
  2. Step 2: Trace second call binarySearch(0, 1)

    mid = (0+1)//2 = 0; nums[0]=1, nums[1]=3; since 1 < 3, recurse binarySearch(1,1)
  3. Step 3: Trace third call binarySearch(1, 1)

    low == high, return 1
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Returned index 1 corresponds to peak element 3 [OK]
Hint: Check mid and mid+1 comparison carefully [OK]
Common Mistakes:
  • Returning mid instead of low/high
  • Off-by-one in mid calculation
  • Confusing which half to recurse
2. Given the following code snippet, what is the final output when running with piles = [3, 6, 7, 11] and h = 8?
from math import ceil

def can_finish(piles, speed, h):
    hours = 0
    for pile in piles:
        hours += ceil(pile / speed)
        if hours > h:
            return false
    return true

def minEatingSpeed(piles, h):
    low, high = 1, max(piles)
    while low < high:
        mid = (low + high) // 2
        if can_finish(piles, mid, h):
            high = mid
        else:
            low = mid + 1
    return low

piles = [3,6,7,11]
h = 8
print(minEatingSpeed(piles, h))
easy
A. 3
B. 4
C. 5
D. 6

Solution

  1. Step 1: Trace binary search iterations

    Initial low=1, high=11. mid=6: can_finish with speed=6 returns true (hours=3+1+2+2=8 ≤8), so high=6. Next mid=(1+6)//2=3: can_finish speed=3 returns false (hours=1+2+3+4=10 >8), so low=4. Next mid=(4+6)//2=5: can_finish speed=5 returns true (hours=1+2+2+3=8 ≤8), so high=5. Next mid=(4+5)//2=4: can_finish speed=4 returns true (hours=1+2+2+3=8 ≤8), so high=4. Now low=4, high=4, loop ends.
  2. Step 2: Return final low value

    The minimum speed is 4.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Tracing confirms minimum speed is 4 [OK]
Hint: Check feasibility at mid speeds carefully [OK]
Common Mistakes:
  • Off-by-one in binary search boundaries
  • Miscounting hours with ceil division
3. Consider the following Python code implementing the min-heap approach to find the kth smallest element in a sorted matrix. Given the matrix [[1,3],[2,4]] and k = 3, what value does the function return?
easy
A. 2
B. 4
C. 3
D. 1

Solution

  1. Step 1: Initialize min-heap with first elements

    Push (1,0,0) and (2,1,0) into heap.
  2. Step 2: Extract elements until count == k

    Pop 1 (count=1), push 3 from row 0; pop 2 (count=2), push 4 from row 1; pop 3 (count=3), return 3.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Third smallest element is 3 [OK]
Hint: Trace heap pops and pushes carefully [OK]
Common Mistakes:
  • Off-by-one counting of popped elements
  • Returning wrong popped value
  • Confusing row and column indices
4. What is the time complexity of the optimized binary search solution for placing m balls in n positions to maximize the minimum distance, where d is the maximum distance between the first and last positions?
medium
A. O(n log d)
B. O(n * d)
C. O(d log n)
D. O(n log n)

Solution

  1. Step 1: Identify outer loop complexity

    Binary search on answer space runs in O(log d) iterations, where d is max distance.
  2. Step 2: Identify inner loop complexity

    Each feasibility check scans positions once, O(n). Total complexity is O(n log d).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Binary search x linear feasibility check = O(n log d) [OK]
Hint: Binary search on distance x linear feasibility check [OK]
Common Mistakes:
  • Confusing d with n in complexity
  • Assuming linear search over distances (O(n*d))
5. Suppose the matrix rows are sorted but columns are not guaranteed to be sorted. Which of the following approaches correctly finds the target value efficiently?
hard
A. Use the staircase search starting from the top-right corner.
B. Use a brute force nested loop to check every element.
C. Perform binary search on each row independently.
D. Sort each column first, then apply staircase search.

Solution

  1. Step 1: Understand matrix constraints

    Only rows are sorted; columns are unsorted, so staircase search assumptions fail.
  2. Step 2: Evaluate approaches

    Binary search on rows works but columns unsorted means target could be anywhere in columns; brute force guarantees correctness.
  3. Step 3: Consider sorting columns

    Sorting columns is expensive and changes matrix; not practical for search.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Brute force is correct though less efficient; others rely on column sorting [OK]
Hint: Without column sorting, staircase search fails [OK]
Common Mistakes:
  • Assuming staircase search works with only row sorting
  • Thinking sorting columns is cheap
  • Believing binary search on rows suffices
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard