891700. Missing Number in Sorted Array of Natural Numbers

Easy

Here is a detailed Markdown blog post for the GeeksforGeeks problem:

Missing Number in Sorted Array of Natural Numbers

Summary

Find the missing number in a sorted array of natural numbers. The input array has one missing number, and you need to find it using binary search.

Detailed Explanation

The approach is straightforward: use binary search to find the missing number. Since the array is sorted, we can start by checking if the middle element is present or not. If it's not present, then we know that all elements before this point are also missing (since they would be less than the first non-missing element). We can repeat this process until we find the correct position of the missing number.

Here's a step-by-step breakdown:

  1. Find the middle element of the array.
  2. Check if the middle element is present in the array. If not, then all elements before this point are also missing.
  3. Recursively apply the same steps to the left half of the array (or the right half, depending on whether the middle element was less than or greater than the first non-missing element).
  4. Repeat step 2 until you find the correct position of the missing number.

Time complexity: O(log n), where n is the size of the input array. Space complexity: O(1), since we only use a constant amount of space to store temporary variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int findMissingNumber(int[] arr) {
    int low = 0, high = arr.length - 1;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (mid >= arr.length || arr[mid] != mid + 1) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    return low;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.