702671. Find k-th missing element

Easy

Find k-th missing element

Summary

Given an array of distinct integers, find the kth missing integer. This problem involves finding a specific element in an array that is not present, and the key concept is array manipulation.

Detailed Explanation

To solve this problem, we can iterate through the array and maintain a count of the missing elements. We start with a variable missing_count set to 0. Then, for each element i in the array, we check if i+1 (the next integer) is present in the array. If it's not, we increment missing_count. Once we reach k-1, we know that the kth missing element is the one just before the next integer, which would be i+k.

Here's a step-by-step breakdown of the solution:

  1. Initialize missing_count to 0.
  2. Iterate through the array:
    • For each element i in the array, check if i+1 (the next integer) is present in the array.
    • If it's not, increment missing_count.
  3. Once we reach k-1, return missing_count.

Time complexity: O(n), where n is the size of the input array.

Space complexity: O(1), as we only use a single variable to keep track of the missing count.

Optimized Solutions

Java

View on GeeksforGeeks
public int findKthMissingElement(int[] arr, int k) {
    int missing_count = 0;
    for (int i : arr) {
        if (!contains(arr, i + 1)) {
            missing_count++;
            if (missing_count == k - 1) {
                return i + k;
            }
        }
    }
    return -1; // or throw an exception
}

private boolean contains(int[] arr, int target) {
    for (int i : arr) {
        if (i == target) {
            return true;
        }
    }
    return false;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.