![]() |
VOOZH | about |
Given an array arr[] of size N - 1 containing numbers between 1, 2... N, except one, the task is to find the missing number.
Examples:
Input: N = 5, arr[] = {2, 3, 1, 5}
Output: 4
Explanation: arr[] contains all numbers from 1 to 5 except 4, therefore the answer is 4.Input: N = 6, arr[] = {4, 5, 1, 2, 3}
Output: 6
Explanation: arr[] contains all numbers from 1 to 6 except 6, therefore the answer is 6.
Approach: To solve the problem, follow the below idea:
The problem can be solved using bitwise XOR operation. We can take the XOR of all the elements of arr[] and all numbers from 1 to N. Except for the missing number, every number from 1 to N will occur two times: once in arr[] and once while iterating from 1 to N. Since taking XOR of any number with itself leads to 0, so the XOR of all the numbers which occur two times will become 0 leaving behind the only number which occurred once while iterating from 1 to N but not in arr[].
Step-by-step algorithm:
Below is the implementation of the algorithm:
4
Time Complexity: O(N), where N is the size of array arr[].
Auxiliary 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.
Example : To demonstrate finding the missing number Using Direct Formula approach
The missing number from the array is: 3
Time Complexity: O(n)
Auxiliary Space: O(1)