πDay 2. Missing in Array π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
You are given an array arr[]
of size n - 1 that contains distinct integers in the range from 1 to n (inclusive).
The array represents a permutation of numbers from 1
to n
with one number missing. Your task is to find the missing number.
π Example Walkthrough:
Example 1:
Input:
arr[] = [1, 2, 3, 5]
Output:
4
Explanation:
All numbers from 1 to 5 should be present. The number 4 is missing.
Example 2:
Input:
arr[] = [8, 2, 4, 5, 3, 7, 1]
Output:
6
Explanation:
All numbers from 1 to 8 should be present. The number 6 is missing.
Example 3:
Input:
arr[] = [1]
Output:
2
Explanation:
Only 1 is present, hence the missing number is 2.
Constraints:
$(1 \leq \text{arr.size()} \leq 10^6)$
$(1 \leq \text{arr[i]} \leq \text{arr.size()} + 1)$
π― My Approach:
Optimal XOR Approach
This approach relies on properties of XOR:
a β a = 0 and a β 0 = a
If you XOR all numbers from
1 to n
and all elements in the array, the duplicate numbers cancel each other out, leaving only the missing number.
Algorithm Steps:
Initialize
x = 0
.XOR all elements of the array with
x
.XOR all numbers from
1
ton
withx
.The result is the missing number.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(n)
, as we make two passes over the array (XOR and loop from 1 to n).Expected Auxiliary Space Complexity:
O(1)
, as we use only a constant amount of additional space.
π Solution Code
Code (C)
int missingNum(int *a, int n){
int x=0;
for(int i=0;i<n;++i) x^=a[i]^(i+1);
return x^(n+1);
}
Code (C++)
class Solution{
public:
int missingNum(vector<int>&a){
int x=0,n=a.size()+1;
for(int i=0;i<a.size();++i) x^=a[i]^(i+1);
return x^n;
}
};
Code (Java)
class Solution {
int missingNum(int[] a) {
int x = 0;
for (int i = 0; i < a.length; ++i) x ^= a[i] ^ (i + 1);
return x ^ (a.length + 1);
}
}
Code (Python)
class Solution:
def missingNum(self, a):
x = 0
for i, v in enumerate(a): x ^= v ^ (i + 1)
return x ^ (len(a) + 1)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated