LeetCode 1539: Kth Missing Positive Number Solution

Master LeetCode problem 1539 (Kth Missing Positive Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1539. Kth Missing Positive Number

Problem Explanation

Explanation

To solve this problem in less than O(n) complexity, we can use binary search. We iterate over the array and for each element arr[i], we calculate how many missing numbers are there between arr[i-1] and arr[i]. Then we use binary search to find the kth missing number.

Algorithm:

  1. Initialize variables left to 0 and right to the last element of the array.
  2. While left is less than right:
    • Calculate the mid element as (left + right) / 2.
    • Calculate the number of missing elements between arr[i-1] and mid.
    • If the count of missing elements is less than k, update left = mid + 1.
    • Otherwise, update right = mid.
  3. Return left + k as the kth missing positive number.

Time Complexity: O(log n) - where n is the length of the input array. Space Complexity: O(1)

Solution Code

class Solution {
    public int findKthPositive(int[] arr, int k) {
        int left = 0, right = arr.length;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] - mid - 1 < k) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left + k;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1539 (Kth Missing Positive Number)?

This page provides optimized solutions for LeetCode problem 1539 (Kth Missing Positive Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1539 (Kth Missing Positive Number)?

The time complexity for LeetCode 1539 (Kth Missing Positive Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1539 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1539 in Java, C++, or Python.

Back to LeetCode Solutions