15% off all plans & roadmaps Use code

See plans

Kth Missing Positive Number

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 <= 1000
  • 1 <= arr[i] <= 1000
  • 1 <= k <= 1000
  • arr[i] < arr[j] for 1 <= 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Set x to 0 and keep a running count of misses, starting from k.
  2. Increase x by 1 on each pass of the loop.
  3. Scan the whole array to see whether x is present.
  4. If x is absent, decrease the remaining count by 1.
  5. 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

TimeO(n * (n + k))
SpaceO(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 x

Approach 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

  1. Walk the array from left to right with its index.
  2. Compute the gap before the current element as value - (i + 1).
  3. If the gap is at least k, return k + i.
  4. 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

TimeO(n)
SpaceO(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 infographic

Solution 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

  1. Set left to 0 and right to n - 1.
  2. While left is at most right, compute mid as left + (right - left) / 2.
  3. If arr[mid] - (mid + 1) is less than k, move left to mid + 1.
  4. Otherwise move right to mid - 1.
  5. When the loop ends, return left + k.

Dry run

Use arr = [3, 5, 6, 9, 12, 15] and k = 8. Here n = 6.

Stepleftrightmidarr[mid]gap = arr[mid] - (mid + 1)gap vs k = 8Action
105266 - 3 = 33 < 8left = 3
23541212 - 5 = 77 < 8left = 5
35551515 - 6 = 99 >= 8right = 4

The loop ends because left = 5 is greater than right = 4. Return left + k = 5 + 8 = 13.

Complexity

TimeO(log n)
SpaceO(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 + k

Common mistakes

  • Using arr[i] - i as the gap. Indices start at 0 but values start at 1, so the expected value at index i is i + 1. Use arr[i] - (i + 1).
  • Returning arr[left] + k or arr[right] + k. The index can equal n after the search, which is out of bounds. Return left + k, which counts the elements below the answer.
  • Setting right = mid in the binary search. The range can stop shrinking and loop forever. Use right = mid - 1 and keep the loop condition left <= 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 + n after 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-ups

Kth 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

Practise it