Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Find the missing number in a sorted array of limited range
Next article icon

Find the only missing number in a sorted array

Last Updated : 12 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

You are given a sorted array of N integers from 1 to N with one number missing find the missing number

Examples: 

Input :ar[] = {1, 3, 4, 5}
Output : 2

Input : ar[] = {1, 2, 3, 4, 5, 7, 8}
Output : 6

A simple solution is to linearly traverse the given array. Find the point where current element is not one more than previous.

An efficient solution is to use binary search. We use the index to search for the missing element and modified binary search. If element at mid != index+1 and this is first missing element then mid + 1 is the missing element. Else if this is not first missing element but ar[mid] != mid+1 search in left half. Else search in right half and if left>right then no element is missing. 

C++
// CPP program to find the only missing element. #include <iostream> using namespace std;  int findmissing(int ar[], int N) {     int l = 0, r = N - 1;     while (l <= r) {          int mid = (l + r) / 2;          // If this is the first element          // which is not index + 1, then          // missing element is mid+1         if (ar[mid] != mid + 1 &&                          ar[mid - 1] == mid)             return mid + 1;          // if this is not the first missing          // element search in left side         if (ar[mid] != mid + 1)             r = mid - 1;          // if it follows index+1 property then          // search in right side         else             l = mid + 1;     }      // if no element is missing     return -1; }  // Driver code int main() {     int arr[] = {1, 2, 3, 4, 5, 7, 8};     int N = sizeof(arr)/sizeof(arr[0]);     cout << findmissing(arr, N);     return 0; } 
Java
// Java program to find  // the only missing element. class GFG { static int findmissing(int [] ar, int N) {          int l = 0, r = N - 1;     while (l <= r)      {         int mid = (l + r) / 2;              // If this is the first element          // which is not index + 1, then          // missing element is mid+1         if (ar[mid] != mid + 1 &&              ar[mid - 1] == mid)             return (mid + 1);              // if this is not the first         // missing element search         // in left side         if (ar[mid] != mid + 1)             r = mid - 1;              // if it follows index+1         // property then search         // in right side         else             l = mid + 1;     }  // if no element is missing return -1; }  // Driver code public static void main(String [] args) {     int arr[] = {1, 2, 3, 4, 5, 7, 8};     int N = arr.length;     System.out.println(findmissing(arr, N)); } }  // This code is contributed  // by Shivi_Aggarwal 
Python
# PYTHON 3 program to find  # the only missing element. def findmissing(ar, N):     l = 0     r = N - 1     while (l <= r):          mid = (l + r) / 2         mid= int (mid)      # If this is the first element      # which is not index + 1, then      # missing element is mid+1         if(ar[mid] != mid + 1 and            ar[mid - 1] == mid):             return (mid + 1)      # if this is not the first      # missing element search      # in left side         elif(ar[mid] != mid + 1):             r = mid - 1      # if it follows index+1      # property then search      # in right side         else:             l = mid + 1          # if no element is missing     return (-1)      def main():     ar= [1, 2, 3, 4, 5, 7, 8]     N = len(ar)     res= findmissing(ar, N)     print (res) if __name__ == "__main__":     main()  # This code is contributed  # by Shivi_Aggarwal 
C#
// C# program to find  // the only missing element. using System;  class GFG { static int findmissing(int []ar,                         int N) {          int l = 0, r = N - 1;     while (l <= r)      {         int mid = (l + r) / 2;              // If this is the first element          // which is not index + 1, then          // missing element is mid+1         if (ar[mid] != mid + 1 &&              ar[mid - 1] == mid)             return (mid + 1);              // if this is not the first         // missing element search         // in left side         if (ar[mid] != mid + 1)             r = mid - 1;              // if it follows index+1         // property then search         // in right side         else             l = mid + 1;     }  // if no element is missing return -1; }  // Driver code public static void Main() {     int []arr = {1, 2, 3, 4, 5, 7, 8};     int N = arr.Length;     Console.WriteLine(findmissing(arr, N)); } }  // This code is contributed  // by Akanksha Rai(Abby_akku) 
JavaScript
<script>  // JavaScript program to find the only missing element.        function findmissing(ar, N) {         var l = 0,           r = N - 1;         while (l <= r) {           var mid = parseInt((l + r) / 2);            // If this is the first element           // which is not index + 1, then           // missing element is mid+1           if (ar[mid] != mid + 1 && ar[mid - 1] == mid)            return mid + 1;            // if this is not the first missing           // element search in left side           if (ar[mid] != mid + 1) r = mid - 1;           // if it follows index+1 property then           // search in right side           else l = mid + 1;         }          // if no element is missing         return -1;       }        // Driver code       var arr = [1, 2, 3, 4, 5, 7, 8];       var N = arr.length;       document.write(findmissing(arr, N));        </script> 
PHP
<?php // PHP program to find  // the only missing element.  function findmissing(&$ar, $N) {     $r = $N - 1;     $l = 0;     while ($l <= $r)     {         $mid = ($l + $r) / 2;          // If this is the first element          // which is not index + 1, then          // missing element is mid+1         if ($ar[$mid] != $mid + 1 &&              $ar[$mid - 1] == $mid)             return ($mid + 1);          // if this is not the first          // missing element search          // in left side         if ($ar[$mid] != $mid + 1)             $r = $mid - 1;          // if it follows index+1          // property then search          // in right side         else             $l = $mid + 1;     }      // if no element is missing     return (-1); }  // Driver Code $ar = array(1, 2, 3, 4, 5, 7, 8); $N = sizeof($ar); echo(findmissing($ar, $N));  // This code is contributed  // by Shivi_Aggarwal ?>  

Output
6

Time Complexity: O(Log n) 
Auxiliary Space: O(1)

Find the only missing number in a sorted array Using Direct Formula approach

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.

Below is the implementation of above approach:

C++
#include <iostream> #include <vector>  using namespace std;  int findMissingNumber(const vector<int>& nums) {     // Calculate the total sum     int n = nums.size() + 1;     int totalSum = n * (n + 1) / 2;      // Calculate sum of all elements in the given array     int arraySum = 0;     for (int num : nums) {         arraySum += num;     }      // Subtract  and return the total sum with the sum of     // all elements in the array     int missingNumber = totalSum - arraySum;      return missingNumber; }  int main() {      vector<int> numbers = { 1, 2, 3, 4, 5, 7, 8 };     int missing = findMissingNumber(numbers);     cout << "The only missing number is: " << missing          << endl;      return 0; } 
Java
import java.util.ArrayList; import java.util.List;  public class Main {      public static int findMissingNumber(List<Integer> nums)     {         // Calculate the total sum         int n = nums.size() + 1;         int totalSum = n * (n + 1) / 2;          // Calculate sum of all elements in the given array         int arraySum = 0;         for (int num : nums) {             arraySum += num;         }          // Subtract and return the total sum with the sum of         // all elements in the array         int missingNumber = totalSum - arraySum;          return missingNumber;     }      public static void main(String[] args)     {         List<Integer> numbers = new ArrayList<>();         numbers.add(1);         numbers.add(2);         numbers.add(3);         numbers.add(4);         numbers.add(5);         numbers.add(7);         numbers.add(8);          int missing = findMissingNumber(numbers);         System.out.println("The only missing number is: "                            + missing);     } } 
Python
def find_missing_number(nums):     # Calculate the total sum     n = len(nums) + 1     total_sum = n * (n + 1) // 2      # Calculate sum of all elements in the given array     array_sum = sum(nums)      # Subtract and return the total sum with the sum of     # all elements in the array     missing_number = total_sum - array_sum      return missing_number   if __name__ == "__main__":     numbers = [1, 2, 3, 4, 5, 7, 8]     missing = find_missing_number(numbers)     print("The only missing number is:", missing) # This code is contributed by Ayush Mishra 
JavaScript
function findMissingNumber(nums) {     // Calculate the total sum     const n = nums.length + 1;     const totalSum = (n * (n + 1)) / 2;      // Calculate sum of all elements in the given array     let arraySum = 0;     for (let num of nums) {         arraySum += num;     }      // Subtract and return the total sum with the sum of     // all elements in the array     const missingNumber = totalSum - arraySum;      return missingNumber; }  function main() {     const numbers = [1, 2, 3, 4, 5, 7, 8];      const missing = findMissingNumber(numbers);     console.log("The only missing number is: " + missing); }  main(); 

Output
The only missing number is: 6 

Time Complexity: O(1) 
Auxiliary Space: O(1)
 



Next Article
Find the missing number in a sorted array of limited range
https://media.geeksforgeeks.org/auth/avatar.png
Anonymous
Improve
Article Tags :
  • Algorithms
  • DSA
  • Experiences
  • Interview Experiences
  • Searching
Practice Tags :
  • Algorithms
  • Searching

Similar Reads

  • Find the missing number in a sorted array of limited range
    Given a sorted array of size n, consisting of integers from 1 to n+1 with one missing. The task is to find the missing element. Examples: Input : arr[] = [1, 3, 4, 5, 6]Output : 2 Input : arr[] = [1, 2, 3, 4, 5, 7, 8, 9, 10]Output : 6 Input: arr[] = [1, 2, 3, 4]Output: 5 Using Linear Search - O(n) t
    11 min read
  • Count of Missing Numbers in a sorted array
    Given a sorted array arr[], the task is to calculate the number of missing numbers between the first and last element of the sorted array. Examples: Input: arr[] = { 1, 4, 5, 8 } Output: 4 Explanation: The missing integers in the array are {2, 3, 6, 7}. Therefore, the count is 4. Input: arr[] = {5,
    9 min read
  • Find the one missing number in range
    Given an array of size n. It is also given that range of numbers is from smallestNumber to smallestNumber + n where smallestNumber is the smallest number in array. The array contains number in this range but one number is missing so the task is to find this missing number. Examples: Input: arr[] = {
    9 min read
  • Kth Missing Positive Number in a Sorted Array
    Given a sorted array of distinct positive integers arr[] and integer k, the task is to find the kth positive number that is missing from arr[]. Examples : Input: arr[] = [2, 3, 4, 7, 11], k = 5Output: 9Explanation: Missing are 1, 5, 6, 8, 9, 10, ... and 5th missing number is 9. Input: arr[] = [1, 2,
    10 min read
  • Find all missing numbers from a given sorted array
    Given a sorted array arr[] of N integers, The task is to find the multiple missing elements in the array between the ranges [arr[0], arr[N-1]]. Examples: Input: arr[] = {6, 7, 10, 11, 13}Output: 8 9 12 Explanation: The elements of the array are present in the range of the maximum and minimum array e
    13 min read
  • Missing in a Sorted Array of Natural Numbers
    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. Write an efficient code to find the missing integer. Examples: Input : arr[] = [1, 2, 3, 4, 6, 7, 8]Output : 5Explanation: The mis
    12 min read
  • Find missing element in a sorted array of consecutive numbers
    Given an array arr[] of n distinct integers. Elements are placed sequentially in ascending order with one element missing. The task is to find the missing element.Examples: Input: arr[] = {1, 2, 4, 5, 6, 7, 8, 9} Output: 3Input: arr[] = {-4, -3, -1, 0, 1, 2} Output: -2Input: arr[] = {1, 2, 3, 4} Out
    7 min read
  • Find the smallest missing number
    Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. Examples: Input: {0, 1, 2, 6, 9}, n = 5, m = 10 Output: 3 Input: {4, 5, 10, 11}, n = 4, m = 12 Output: 0 Input: {0, 1, 2, 3}, n = 4, m =
    15 min read
  • Find the missing number in Arithmetic Progression
    Given an array arr[] that represents elements of arithmetic progression in order. One element is missing in the progression, find the missing number. Note: An element will always exist that, upon inserting into a sequence forms Arithmetic progression. If the given sequence already forms a valid comp
    15+ min read
  • Find missing number in another array which is shuffled copy
    Given an array 'arr1' of n positive integers. Contents of arr1[] are copied to another array 'arr2', but numbers are shuffled and one element is removed. Find the missing element(without using any extra space and in O(n) time complexity). Examples : Input : arr1[] = {4, 8, 1, 3, 7}, arr2[] = {7, 4,
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences