Kth Missing Positive Number
Kth Missing Positive Number is a easy binary search problem solved with the bisect pattern.
The best approach, optimal (binary search on the missing count), runs in O(log n) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (count up from 1) up.
Problem
You are given an array arr of positive integers in strictly increasing order and a positive integer k.
Think of the positive integers 1, 2, 3, ... that do not appear in arr, listed in increasing order. Return the k-th number of that list.
Examples
Example 1
- Input
arr = [3,4,7,10], k = 4- Output
6- Why
- The positive integers that are not in arr are 1, 2, 5, 6, 8, 9, 11, ... The fourth of them is 6.
Example 2
- Input
arr = [1,2,3], k = 2- Output
5- Why
- Nothing is missing before 3, so the missing numbers are 4, 5, 6, ... and the second one is 5.
Example 3
- Input
arr = [2,5,6], k = 1- Output
1- Why
- 1 is not in arr, so it is the first missing positive integer.
Constraints
1 <= arr.length <= 10001 <= arr[i] <= 10001 <= k <= 1000arr[i] < arr[i + 1]for every valid i (strictly increasing)
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 23 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (count up from 1) | O(n + k) | O(1) |
| Linear scan of the missing counts | O(n) | O(1) |
| Optimal (binary search on the missing count) | O(log n) | O(1) |
1Brute force (count up from 1)
O(n + k)x goes up to the answer, which is at most n + k: every number up to it is either one of the n elements or one of the k missing numbers.O(1)Only the pointer, the counter and x.Walk through the positive integers 1, 2, 3, ... with a pointer into arr. If the current number equals arr[p], it is present, so move the pointer on. Otherwise it is missing: count it, and when the count reaches k, that number is the answer. Since arr is sorted, a single pointer is enough to know whether a number is present.
- Set p = 0 and missing = 0.
- For x = 1, 2, 3, ...: if p < arr.length and arr[p] == x, move p forward.
- Otherwise add one to missing; if missing == k, return x.
class Solution {
public int findKthPositive(int[] arr, int k) {
int p = 0, missing = 0;
for (int x = 1; ; x++) {
if (p < arr.length && arr[p] == x) {
p++;
} else {
missing++;
if (missing == k) return x;
}
}
}
}class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
p = missing = 0
x = 0
while True:
x += 1
if p < len(arr) and arr[p] == x:
p += 1
else:
missing += 1
if missing == k:
return xclass Solution {
public:
int findKthPositive(vector<int>& arr, int k) {
int p = 0, missing = 0;
for (int x = 1; ; x++) {
if (p < (int) arr.size() && arr[p] == x) {
p++;
} else {
missing++;
if (missing == k) return x;
}
}
}
};function findKthPositive(arr, k) {
let p = 0, missing = 0;
for (let x = 1; ; x++) {
if (p < arr.length && arr[p] === x) {
p++;
} else {
missing++;
if (missing === k) return x;
}
}
}2Linear scan of the missing counts
O(n)One pass over arr with O(1) work per element.O(1)Only the loop index.Jump over whole gaps instead of single numbers. The numbers 1 to arr[i] include i + 1 elements of arr (arr[0] to arr[i]), so exactly arr[i] - (i + 1) numbers below arr[i] are missing. Scan i from left to right and stop at the first index where that count reaches k. Then the k-th missing number sits in the gap just before arr[i], and i elements of arr lie below it, so it equals k + i. If no index qualifies, the answer comes after the last element and equals k + n by the same argument.
- For i = 0 to n - 1: if arr[i] - i - 1 >= k, return k + i.
- Return k + n.
class Solution {
public int findKthPositive(int[] arr, int k) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] - i - 1 >= k) return k + i;
}
return k + arr.length;
}
}class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
for i in range(len(arr)):
if arr[i] - i - 1 >= k:
return k + i
return k + len(arr)class Solution {
public:
int findKthPositive(vector<int>& arr, int k) {
for (int i = 0; i < (int) arr.size(); i++) {
if (arr[i] - i - 1 >= k) return k + i;
}
return k + arr.size();
}
};function findKthPositive(arr, k) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] - i - 1 >= k) return k + i;
}
return k + arr.length;
}3Optimal (binary search on the missing count)
O(log n)Each step halves the range [lo, hi], which starts with n + 1 positions.O(1)Only lo, hi and mid.The count missing(i) = arr[i] - i - 1 never goes down as i grows, because the array is strictly increasing: arr[i + 1] is at least arr[i] + 1. So the indexes split into a left part with missing(i) < k and a right part with missing(i) >= k, and binary search finds the boundary lo, the first index of the right part (lo = n when it is empty). Exactly lo elements of arr are smaller than the answer, and k numbers are missing up to it, so the answer is lo + k.
- Set lo = 0 and hi = arr.length (the boundary is somewhere in [lo, hi]).
- While lo < hi: mid = (lo + hi) / 2. If arr[mid] - mid - 1 < k, the boundary is right of mid: lo = mid + 1. Otherwise hi = mid.
- Return lo + k.
class Solution {
public int findKthPositive(int[] arr, int k) {
int lo = 0, hi = arr.length;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (arr[mid] - mid - 1 < k) lo = mid + 1;
else hi = mid;
}
return lo + k;
}
}class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
lo, hi = 0, len(arr)
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] - mid - 1 < k:
lo = mid + 1
else:
hi = mid
return lo + kclass Solution {
public:
int findKthPositive(vector<int>& arr, int k) {
int lo = 0, hi = arr.size();
while (lo < hi) {
int mid = (lo + hi) / 2;
if (arr[mid] - mid - 1 < k) lo = mid + 1;
else hi = mid;
}
return lo + k;
}
};function findKthPositive(arr, k) {
let lo = 0, hi = arr.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (arr[mid] - mid - 1 < k) lo = mid + 1;
else hi = mid;
}
return lo + k;
}Edge cases to test
- The answer comes before the first element (arr[0] > k): the answer is simply k
- Nothing is missing inside arr (arr = [1, 2, ..., n]): the answer is n + k
- The answer lies after the last element: count on from arr[n - 1] past every number that is still missing
- A single element, either 1 or larger than k
- The answer can be as large as arr.length + k, about 2000
Hints
Hint 1
Walking 1, 2, 3, ... and skipping the numbers in arr works because both lists are in increasing order.
Hint 2
Before position i (0-based), the numbers 1 to arr[i] contain i + 1 elements of arr, so exactly arr[i] - (i + 1) of them are missing.
Hint 3
That missing count never decreases as i grows. Binary search for the first index whose count is at least k; if it is lo, the answer is lo + k.
FAQ
What is the best time complexity for Kth Missing Positive Number?
Optimal (binary search on the missing count) runs in O(log n) time and O(1) extra space. Each step halves the range [lo, hi], which starts with n + 1 positions.
Which pattern does Kth Missing Positive Number use?
It is a binary search problem that uses the bisect pattern. Other problems with the same pattern: bisect_left, bisect_right, Search Insert Position, Floor in a Sorted Array.
Is there a brute force solution for Kth Missing Positive Number?
Yes. Brute force (count up from 1) takes O(n + k) time and O(1) space. Walk through the positive integers 1, 2, 3, ...
Which edge cases should I test for Kth Missing Positive Number?
The answer comes before the first element (arr[0] k): the answer is simply k; Nothing is missing inside arr (arr = [1, 2, ..., n]): the answer is n + k; The answer lies after the last element: count on from arr[n - 1] past every number that is still missing; A single element, either 1 or larger than k; The answer can be as large as arr.length + k, about 2000.