Most Efficient Way to Find a Missing Number in an array
Last Updated :
06 Jan, 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:
C++
#include <iostream>
using namespace std;
int findMissingNumbers( int arr[], int n)
{
int XOR = 0;
for ( int i = 0; i < n - 1; i++) {
XOR ^= arr[i];
}
for ( int i = 1; i < n + 1; i++) {
XOR ^= i;
}
return XOR;
}
int main()
{
int arr[] = { 1, 2, 4, 5 };
int n = 5;
cout << findMissingNumbers(arr, n) << endl;
return 0;
}
|
Java
public class MissingNumberFinder {
public static int findMissingNumbers( int [] arr, int n) {
int XOR = 0 ;
for ( int i = 0 ; i < n - 1 ; i++) {
XOR ^= arr[i];
}
for ( int i = 1 ; i < n + 1 ; i++) {
XOR ^= i;
}
return XOR;
}
public static void main(String[] args) {
int [] arr = { 1 , 2 , 4 , 5 };
int n = 5 ;
System.out.println(findMissingNumbers(arr, n));
}
}
|
Python3
def find_missing_numbers(arr, n):
XOR = 0
for i in range (n - 1 ):
XOR ^ = arr[i]
for i in range ( 1 , n + 1 ):
XOR ^ = i
return XOR
if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 5 ]
n = 5
print (find_missing_numbers(arr, n))
|
C#
using System;
public class MissingNumberFinder
{
public static int FindMissingNumbers( int [] arr, int n)
{
int XOR = 0;
for ( int i = 0; i < n - 1; i++)
{
XOR ^= arr[i];
}
for ( int i = 1; i < n + 1; i++)
{
XOR ^= i;
}
return XOR;
}
public static void Main()
{
int [] arr = {1, 2, 4, 5};
int n = 5;
Console.WriteLine(FindMissingNumbers(arr, n));
}
}
|
Javascript
function findMissingNumbers(arr, n) {
let XOR = 0;
for (let i = 0; i < n - 1; i++) {
XOR ^= arr[i];
}
for (let i = 1; i < n + 1; i++) {
XOR ^= i;
}
return XOR;
}
const arr = [1, 2, 4, 5];
const n = 5;
console.log(findMissingNumbers(arr, n));
|
Time Complexity : O(N)
Auxillary space: O(1)
Share your thoughts in the comments
Please Login to comment...