VOOZH about

URL: https://www.geeksforgeeks.org/dsa/most-efficient-way-to-find-a-missing-number-in-an-array/

⇱ Most Efficient Way to Find a Missing Number in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Most Efficient Way to Find a Missing Number in an array

Last Updated : 24 May, 2024

Have you wondered which is the most efficient way for a popular problem to find a missing Number? well in this post we are going to discuss this phenomenon in brief.

First, let's discuss the problem statement:

Given an array of numbers from 1 to N (both inclusive). The size of the array is N-1. The numbers are randomly added to the array, there is one missing number in the array from 1 to N. What is the quickest way to find that missing number?

An approach using the XOR operator:

  • We can use the XOR operation which is safer than summation because in programming languages if the given input is large it may overflow and may give wrong answers.
  • Before going to the solution, know that A xor A = 0. So if we XOR two identical numbers the value is 0.
  • Now, XORing [1..n] with the elements present in the array cancels the identical numbers. So in the end we will get the missing number.

How the XOR operator makes this algorithm efficient:

XOR has certain properties 

  • Assume a1 ⊕ a2 ⊕ a3 ⊕ . . . ⊕ an = a and a1 ⊕ a2 ⊕ a3 ⊕ . . . ⊕ an-1 = b
  • Then a ⊕ b = an
  • X ^ X = 0, i.e. Xor of the same values is zero.

Below is the implementation of the above idea:


Output
3

Time Complexity : O(N)
Auxillary space: O(1)

Most Efficient Way to Find a Missing Number in an array ( in constant space and constant time)

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:


Output
The only missing number is: 8

Time Complexity:O(1)

Auxiliary Space: O(1)


Comment
Article Tags: