Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Home / DeveloperSection / Forums / Single Number find
Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Ravi Vishwakarma
12-Jun-2024Let's write code to find a single number from the array, we use the XOR technique to solve this problem in C#.
If I take the array [2, 2, 1].
Step-by-Step Execution
Initialization:
result = 0
result
initialized to0
.First Iteration (
num = 2
):result ^= 2
which meansresult = result ^ 2
0 ^ 2 = 2
(since0 XOR anything
equalsthat thing
)result = 2
Second Iteration (
num = 2
):result ^= 2
which meansresult = result ^ 2
2 ^ 2 = 0
(sincea XOR a = 0
)result = 0
Third Iteration (
num = 1
):result ^= 1
which meansresult = result ^ 1
0 ^ 1 = 1
(since0 XOR anything
equalsthat thing
)result = 1
Final Result
return result;
1