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 = 0resultinitialized to0.First Iteration (
num = 2):result ^= 2which meansresult = result ^ 20 ^ 2 = 2(since0 XOR anythingequalsthat thing)result = 2Second Iteration (
num = 2):result ^= 2which meansresult = result ^ 22 ^ 2 = 0(sincea XOR a = 0)result = 0Third Iteration (
num = 1):result ^= 1which meansresult = result ^ 10 ^ 1 = 1(since0 XOR anythingequalsthat thing)result = 1Final Result
return result;1