![]() |
VOOZH | about |
Given an array of n unique integers where each element in the array is in range [1, n]. The array has all distinct elements and size of an array is (n-2). Hence Two numbers from the range are missing from this array. Find the two missing numbers.
Examples:
Input : arr[] = {1, 3, 5, 6}, n = 6
Output : 2 4
Input : arr[] = {1, 2, 4}, n = 5
Output : 3 5
Input : arr[] = {1, 2}, n = 4
Output : 3 4
Find Two Missing Numbers | Set 1 (An Interesting Linear Time Solution)
We have discussed two methods to solve this problem in above article. The method 1 requires O(n) extra space and method 2 can causes overflow. In this post, a new solution is discussed. The solution discussed here is O(n) time, O(1) extra space and causes no overflow.
Below are steps.
XOR = (1 ^ 3 ^ 5 ^ 6) ^ (1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6)
Ex: Elements in arr[] with bit set: {3, 6}
Elements from 1 to n with bit set {2, 3, 6}
Result of XOR'ing all these is x = 2.Ex: Elements in arr[] with bit not set: {1, 5}
Elements from 1 to n with bit not set {1, 4, 5}
Result of XOR'ing all these is y = 4
Below is the implementation of above steps.
Output:
Two Missing Numbers are 2 4
Time Complexity : O(n)
Auxiliary Space : O(1)
No integer overflow