VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-missing-number-in-a-sorted-array/

⇱ Missing in a Sorted Array of Natural Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Missing in a Sorted Array of Natural Numbers

Last Updated : 21 Jul, 2025

Given a sorted array arr[] of n-1 integers, these integers are in the range of 1 to n. There are no duplicates in the array. One of the integers is missing in the array. Find the missing integer. 
Examples:

Input : arr[] = [1, 2, 3, 4, 6, 7, 8]
Output : 5
Explanation: The missing integer in the above array is 5

Input : arr[] = [1, 2, 3, 4, 5, 6, 8, 9]
Output : 7
Explanation: The missing integer in the above array is 7

[Naive Approach] - Nested Loops - O(n^2) Time and O(1) Space

The idea is to use two nested loops, where the outer one iterate from 1 to n, and inner one iterate for each of the array arr[] elements, if the value in outer loop in not found in array arr[], return the value, else iterate to the next value.


Output
5

[Better approach 1] - Comparing the difference between index and elements - O(n) Time and O(1) Space

The idea for this approach is to compare the index and element on that index of the sorted array. If the difference between the index and element on that index is greater than 1 then the missing element is index + 1. If the difference between the index and the element for all index is 1 then the missing element is n.


Output
5

[Better approach 2] - Using Formula for Sum of n terms- O(n) Time and O(1) Space

In this approach we will create Function to find the missing number using the sum of natural numbers formula. First we will Calculate the total sum of the first N natural numbers using formula n * (n + 1) / 2. Now we calculate sum of all elements in given array. Subtract the total sum with sum of all elements in given array and return the missing number.


Output
5

Expected Approach - Using Binary Search - O(log(n)) Time and O(1) Space

The idea is that in a perfectly consecutive sequence starting from 1, the difference between each element and its index is always 1.
When a number is missing, this difference stays 1 before the missing number and becomes 2 after it.
By using binary search, we find the point where this shift occurs. The missing number is one more than the element just before the shift.


Output
5
Comment
Article Tags:
Article Tags: