15% off all plans & roadmaps Use code
See plansKth Missing Positive Number
- LeetCode 1539
- Easy
- Binary Search Patterns
- On Sorted Array/List
Updated
TL;DR: You get a sorted array of distinct positive integers and a number k, and you must return the kth positive integer that is absent from the array. The count of missing numbers before each index never decreases, so you can binary search for the point where that count reaches k.
Problem
You receive an array arr of positive integers. The values are sorted in strictly increasing order, so no value repeats. You also receive an integer k.
Return the kth positive integer that does not appear in arr.
Example 1
Input: arr = [2,3,4,7,11], k = 5 Output: 9 Explanation: The positive integers missing from the array are [1,5,6,8,9,10,12,13,...]. The fifth of them is 9.
Example 2
Input: arr = [1,2,3,4], k = 2 Output: 6 Explanation: The positive integers missing from the array are [5,6,7,...]. The second of them is 6.
Constraints
1 <= arr.length <= 10001 <= arr[i] <= 10001 <= k <= 1000arr[i] < arr[j]for1 <= i < j <= arr.length
Constraints that matter
- The array has at most 1000 elements, so an O(n * (n + k)) brute force still runs, but it does not match the follow-up. Interviewers expect the sorted order to be used.
- Values can be as large as 1000 while k can be 1000, so the answer can reach about 2000. You cannot afford to test every candidate against the whole array when n is large.
- Because the array is strictly increasing, the number of missing values before each index never goes down. That monotone property is what makes binary search valid.
- The follow-up asks for less than O(n). Only a method that skips elements, such as binary search, meets that bound.
Hints
Hint 1
Start with the question the problem really asks.
Hint 2
Walk through the positive integers from 1, and check whether each one appears in the array.
Solution
Intuition
Start with the question the problem really asks. You want the position of the answer on the number line. Each array element sits at a known value, and the array tells you how many positive integers lie below it that are absent. That count is the number of gaps you have passed.
Picture a fence where some numbered posts were removed. The surviving posts are the array, and the count of removed numbers before each post only grows, so you binary search for the first post where that count reaches k.
Look at index i with value arr[i]. If nothing were missing, the value at index i would be i + 1. So the count of missing positives below arr[i] is arr[i] - (i + 1). This quantity is non-decreasing across the array, since each step forward adds at least one to the value and exactly one to the expected value.
Because the gap count only grows, you can ask a yes or no question at any index: have we already skipped at least k numbers by this point? The answer flips from no to yes exactly once. That single flip point is what binary search on a sorted list finds.
Worked example
Input: arr = [3, 5, 6, 9, 12, 15], k = 8 Output: 13 Explanation: The missing positive integers in order are 1, 2, 4, 7, 8, 10, 11, 13. The eighth one is 13. Every approach below should land on this value.
Approach 1: Brute force
Walk through the positive integers from 1, and check whether each one appears in the array. Each absent candidate counts toward k, and you stop when the count hits zero. The check is a linear scan, so each candidate costs a full pass over the array. This is what a beginner writes first, and it needs no insight about the sorted order.
Steps
- Set x to 0 and keep a running count of misses, starting from k.
- Increase x by 1 on each pass of the loop.
- Scan the whole array to see whether x is present.
- If x is absent, decrease the remaining count by 1.
- Stop when the remaining count reaches zero and return x.
Dry run
Use arr = [3, 5, 6, 9, 12, 15] and k = 8. Start with x = 0 and remaining = 8.
- x = 1 is absent, remaining = 7.
- x = 2 is absent, remaining = 6.
- x = 3 is present, skip.
- x = 4 is absent, remaining = 5.
- x = 5 is present, skip.
- x = 6 is present, skip.
- x = 7 is absent, remaining = 4.
- x = 8 is absent, remaining = 3.
- x = 9 is present, skip.
- x = 10 is absent, remaining = 2.
- x = 11 is absent, remaining = 1.
- x = 12 is present, skip.
- x = 13 is absent, remaining = 0.
The loop stops at x = 13, which matches the expected output.
Complexity
| Time | O(n * (n + k)) |
|---|---|
| Space | O(1) |
Let n be the length of arr. The answer is at most n + k, so the outer loop runs at most n + k times. Each iteration performs a membership scan that costs up to n steps, which gives O(n * (n + k)). The code stores only x and a counter, so the extra space is O(1).
PythonTested in our runner
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
x = 0
while k > 0:
x += 1
# linear membership check
if x not in arr:
k -= 1
return xApproach 2: Linear scan of gaps
The brute force rechecks the whole array for every candidate, and most of that work repeats. Since the array is sorted, you can measure the gap before each element in one pass. At index i the number of missing values below arr[i] is arr[i] - (i + 1). The first index where that gap reaches k puts the answer before arr[i], and if no index qualifies, the answer lies after the last element.
Steps
- Walk the array from left to right with its index.
- Compute the gap before the current element as value - (i + 1).
- If the gap is at least k, return k + i.
- If the loop finishes, return k + n, because every gap was too small.
Dry run
Use arr = [3, 5, 6, 9, 12, 15] and k = 8.
- i = 0, value 3, gap 2, below 8.
- i = 1, value 5, gap 3, below 8.
- i = 2, value 6, gap 3, below 8.
- i = 3, value 9, gap 5, below 8.
- i = 4, value 12, gap 7, below 8.
- i = 5, value 15, gap 9, at least 8. Return k + i = 8 + 5 = 13.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the length of arr. The loop visits each element at most once and does constant work per element, so the time is O(n). The code keeps only the loop index and the current value, so the space is O(1). This approach meets the basic requirement but not the sublinear follow-up.
PythonTested in our runner
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
for i, value in enumerate(arr):
# numbers missing before arr[i]
if value - (i + 1) >= k:
return k + i
return k + len(arr)The On Sorted Array/List infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
On Sorted Array/List
Part of Binary Search Patterns
Approach 3: Binary search on the gap countOptimalOn Sorted Array/List
The linear scan still reads every element, but you only need the boundary where the gap first reaches k. Binary search finds that boundary in logarithmic steps. At each probe, a gap below k means the answer lies after mid, and otherwise it lies at or before mid. When the search ends, left equals the number of elements smaller than the answer, so the answer is left + k.
Steps
- Set left to 0 and right to n - 1.
- While left is at most right, compute mid as left + (right - left) / 2.
- If arr[mid] - (mid + 1) is less than k, move left to mid + 1.
- Otherwise move right to mid - 1.
- When the loop ends, return left + k.
Dry run
Use arr = [3, 5, 6, 9, 12, 15] and k = 8. Here n = 6.
| Step | left | right | mid | arr[mid] | gap = arr[mid] - (mid + 1) | gap vs k = 8 | Action |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 6 | 6 - 3 = 3 | 3 < 8 | left = 3 |
| 2 | 3 | 5 | 4 | 12 | 12 - 5 = 7 | 7 < 8 | left = 5 |
| 3 | 5 | 5 | 5 | 15 | 15 - 6 = 9 | 9 >= 8 | right = 4 |
The loop ends because left = 5 is greater than right = 4. Return left + k = 5 + 8 = 13.
Complexity
| Time | O(log n) |
|---|---|
| Space | O(1) |
Let n be the length of arr, and each probe halves the range of candidate indices, so the loop runs about log2(n) + 1 times. Each probe does constant work, so the time is O(log n), and the code keeps only left, right and mid, so the space is O(1). This meets the follow-up because it never reads more than a logarithmic number of elements.
PythonTested in our runner
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
# gap of missing numbers before arr[mid]
if arr[mid] - (mid + 1) < k:
left = mid + 1
else:
right = mid - 1
return left + kCommon mistakes
- Using
arr[i] - ias the gap. Indices start at 0 but values start at 1, so the expected value at index i is i + 1. Usearr[i] - (i + 1). - Returning
arr[left] + korarr[right] + k. The index can equal n after the search, which is out of bounds. Returnleft + k, which counts the elements below the answer. - Setting
right = midin the binary search. The range can stop shrinking and loop forever. Useright = mid - 1and keep the loop conditionleft <= right. - Comparing the gap with
<=instead of<. The search then moves past the element that holds the boundary and returns one too large. Keep the test as gap < k for the move right. - Writing the brute force with a membership test inside a loop that restarts from 1 for each k. This repeats work that the linear scan does once. Count gaps in a single pass instead.
- Forgetting that the answer can fall after the last element. A linear loop that only returns inside the array misses this case. Return
k + nafter the loop ends.
Edge cases
- arr = [2], k = 1 returns 1, since 1 is the only gap before the first element.
- arr = [1, 2, 3], k = 1 returns 4, because the array covers 1 to 3 and the answer lies after the last element.
- arr = [1000], k = 1000 returns 1001. The 999 values from 1 to 999 are missing, so the 1000th missing value is 1001.
- arr = [1], k = 1 returns 2, the first missing positive after an array that starts with 1.
- arr = [5, 6, 7], k = 3 returns 3. Only gaps before 5 count, and there are four of them, so the third missing value is 3.
- A single-element array with a large gap, such as arr = [1000], k = 1, returns 1 because the first missing value is before the element.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Kth Missing Positive Number, with how to answer them.
Unlock the follow-upsKth Missing Positive Number FAQ
What is the time complexity of Kth Missing Positive Number?
The optimal binary search solution runs in O(log n) time, where n is the length of arr. The linear scan runs in O(n) time, and the brute force runs in O(n * (n + k)) time because each candidate costs a full scan.
Why use binary search for Kth Missing Positive Number?
The count of missing values before each index is arr[i] - (i + 1), and that count never decreases. A monotone yes or no test on a sorted list is the setup for binary search. It lets you find the boundary without reading every element.
Can Kth Missing Positive Number be solved in O(1) extra space?
Yes. The binary search keeps only left, right and mid, and the linear scan keeps only an index. Neither approach builds a set or an array of gaps.
Why does the answer equal left + k in the binary search?
When the loop ends, left counts the array elements that lie below the answer. Each of those elements takes one slot in the positive integers, so the answer sits k positions past them. That gives left + k.
Why does the linear scan return k + i?
The first index i whose gap reaches k means the answer falls right before arr[i]. Exactly i array elements lie below the answer, so the answer is k + i.
Asked at
See which companies ask this — Pro
Related problems
- Binary Search · same technique: On Sorted Array/List
- Search Insert Position · same technique: On Sorted Array/List
- Sqrt(x) · same technique: On Sorted Array/List
- Guess Number Higher or Lower · same technique: On Sorted Array/List
- First Bad Version · same technique: On Sorted Array/List
- Koko Eating Bananas · next harder, same pattern
- Search in Rotated Sorted Array · same pattern: Binary Search Patterns
- Find Minimum in Rotated Sorted Array · same pattern: Binary Search Patterns
- Search a 2D Matrix · same pattern: Binary Search Patterns
- Find K Closest Elements · same pattern: Binary Search Patterns