![]() |
VOOZH | about |
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?
A xor A = 0. So if we XOR two identical numbers the value is 0.XOR has certain properties
Below is the implementation of the above idea:
3
Time Complexity : O(N)
Auxillary space: O(1)
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.
The only missing number is: 8
Time Complexity:O(1)
Auxiliary Space: O(1)