Skip to content

Commit dc68ae3

Browse files
authored
Create Missing Number
1 parent 5b92cbb commit dc68ae3

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

LeetCode/Missing Number

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// link - https://leetcode.com/problems/missing-number/
2+
3+
4+
// Approach:
5+
// Since the array contains distinct numbers in the range [0, n] hence if we calculate xor of all the numbers in this
6+
// range and then xor it with the actual elements present in the array it will give us the element which is missing.
7+
// This is because x ^ x = 0, so all the numbers will result in 0 except the one which is missing.
8+
9+
class Solution {
10+
public int missingNumber(int[] nums) {
11+
int n = nums.length;
12+
int ans = n;
13+
14+
for (int i = 0; i < n; i++) {
15+
ans ^= nums[i] ^ i;
16+
}
17+
return ans;
18+
}
19+
}

0 commit comments

Comments
 (0)