Coding Interview PatternsKth Missing Positive Number
EasyCyclic Sort
Kth Missing Positive Number
Explanation & Solution
Description
Given an array arr of positive integers sorted in strictly increasing order, and an integer k, return the k-th positive integer that is missing from this array.
Input:arr = [2, 3, 4, 7, 11], k = 5
0
2
1
3
2
4
3
7
4
11
Output: 9
Explanation: The missing positives in order are: 1, 5, 6, 8, 9, 10... The 5th missing is 9.
Constraints
1 <= arr.length <= 10001 <= arr[i] <= 10001 <= k <= 1000arr[i] < arr[i+1]
Approach
Cyclic Sort pattern
1. The Counting Approach
- Iterate through every positive integer starting from 1
- Maintain a pointer
iintoarrand a count of missing numbers found
2. For Each Candidate Number
- If the current number
numequalsarr[i], it is present — advanceiand continue - Otherwise, the number is missing — increment
missingCount - When
missingCount === k, return the currentnum
3. Why Sorted Order Helps
- Because
arris sorted, comparing the candidate witharr[i]in order is sufficient - There is no need to search or use a hash set
4. When the Answer Exceeds the Array
- If
kis large enough that all ofarris exhausted, the loop continues counting missing positives beyondarr[arr.length - 1] - The pointer
istops advancing once past the end ofarr, and every subsequentnumis missing
🧠 Key Insight
- A binary search approach can solve this in O(log n) by counting how many numbers up to
arr[m]are missing (arr[m] - m - 1), but the linear scan is easier to visualize and is fast enough for the given constraints
Time
O(n + k)at most n comparisons with arr plus up to k missing countsSpace
O(1)two integer variablesVisualization
Input:
[2, 3, 4, 7, 11], k = 5
—
Press ▶ or use ← → to step through
Pointer iPointer jProcessedDone
11 steps