Kth Missing Positive Number - Complete Solution Guide
Kth Missing Positive Number is LeetCode problem 1539, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given an array arr of positive integers sorted in a strictly increasing order , and an integer k . Return the k th positive integer that is missing from this array. Example 1: Input: arr = [2,3,4,7,11], k = 5 Output: 9 Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5 th missing positive integer is 9. Example 2: Input: arr = [1,2,3,4], k = 2 Output: 6 Explanation: The missing positive integers are [5,6,7,...]. The 2 nd missing positive integer is 6. Constraints: 1 <=
Detailed Explanation
The problem asks you to find the kth positive integer that is missing from a sorted array of positive integers. The input is an array `arr` containing strictly increasing positive integers and an integer `k`. The output is the kth positive integer that's missing from the array. For example, if `arr` is [2, 3, 4, 7, 11] and `k` is 5, the missing positive integers are [1, 5, 6, 8, 9, 10, 12, 13...], and the 5th missing positive integer is 9.
Solution Approach
The solution uses a linear scan approach. It maintains two pointers: one iterates through the input array (`i`), and another keeps track of the expected positive integer (`expected`). The algorithm iteratively compares the current element in the array with the expected integer. If they match, it means that integer is present, and we move to the next expected integer. If they don't match, it indicates a missing integer; we increment a `missing` counter and the `expected` integer. This process continues until `missing` reaches `k`, at which point `expected` holds the kth missing positive integer.
Step-by-Step Algorithm
- Initialize `missing` to 0, `expected` to 1, and `i` to 0 (index for the array).
- Iterate while `missing` is less than `k`:
- If `i` is within the array bounds and `arr[i]` equals `expected`, increment `i` (the expected number is present).
- Otherwise, increment `missing` (a number is missing).
- In either case, if `missing` is still less than `k`, increment `expected` (move to the next expected number).
- After the loop, `expected` will hold the kth missing positive integer.
Key Insights
- The array is sorted, allowing us to efficiently check for missing numbers.
- We can use a two-pointer approach (one for the array and one for the expected positive integer) to iterate and count missing numbers.
- No complex data structures are needed; we can solve this problem using only a few integer variables.
Complexity Analysis
Time Complexity: O(n + k)
Space Complexity: O(1)
Topics
This problem involves: Array, Binary Search.
Companies
Asked at: Arista Networks, Morgan Stanley.