You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
- Given a set of integers `nums`, which originally contains all the numbers from 1 to n.
5
+
- Due to some error, one of the numbers in `nums` got duplicated to another number in the set
6
+
- This results in repetition of one number and loss of another number.
7
+
8
+
Find the number that occurs twice and the number that is missing and return them in the form of an array.
9
+
10
+
**Example:**
11
+
>**Input:** nums = [1,2,2,4]\
12
+
**Output:**[2,3]
13
+
14
+
[set-mismatch on leetcode](https://leetcode.com/problems/set-mismatch/description/)
15
+
16
+
## Solution
17
+
### Intuition
18
+
Use xor to find the repeated and missing values.
19
+
20
+
### Approach
21
+
since all the number are from 1 - n we traverse from 1 - n and xor all the values and xor them with the array elements, we will end up with the xor of the missing element and repeated element
22
+
23
+
```x
24
+
example:
25
+
arr = [6,4,5,2,1,7,4]
26
+
27
+
result_xor =
28
+
(1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7) ^
29
+
(6 ^ 4 ^ 5 ^ 2 ^ 1 ^ 7 ^ 4)
30
+
= 3 ^ 4
31
+
```
32
+
33
+
now based on the least significant set bit ($i^{th}$ bit) in the resulting XOR we can divide the number array into 2 parts one part with the $i^{th}$ bit set and the other set with $i^{th}$ bit is not set.
34
+
35
+
```x
36
+
Why does this work?
37
+
```
38
+
Well since if the ith bit is set in the result_xor it means that $i^{th}$ bit is set in only one of the 2 numbers forming the xor hence when we partition the array into 2 parts we will end up with 2 xors one having the missing number and one having the repeated number.
39
+
40
+
```x
41
+
from the above example we have
42
+
result_xor = 3 ^ 4 = 7
43
+
in 7 0th bit is set hence i = 0
44
+
45
+
so we divide the array and index into 2 parts based
46
+
on the rightmost bit (p1 is part1(right bit 0) and
47
+
p2 is part2(right bit 1))
48
+
49
+
the array --- the indices(1-indexed)
50
+
6 - 110 - p1 1 - 001 - p2
51
+
4 - 100 - p1 2 - 010 - p1
52
+
5 - 101 - p2 3 - 011 - p2
53
+
2 - 010 - p1 4 - 100 - p1
54
+
1 - 001 - p2 5 - 101 - p2
55
+
7 - 111 - p2 6 - 110 - p1
56
+
4 - 100 - p1 7 - 111 - p2
57
+
58
+
xor_p1 = (6 ^ 4 ^ 2 ^ 4) ^ (2 ^ 4 ^ 6) = 4
59
+
xor_p2 = (5 ^ 1 ^ 7) ^ (1 ^ 3 ^ 5 ^ 7) = 3
60
+
```
61
+
62
+
Iterate over the array again to check which one of xor_p1 and xor_p2 is present in the array and return answer appropriately.
63
+
64
+
### Time Complexity
65
+
$O(n)$ -> since the array is being traversed in one direction
66
+
67
+
### Space Complexity
68
+
$O(1)$ -> no extra space used only integers to store XOR values
0 commit comments