🚀Day 05/180 (Bit Manipulation) 136. Single Number
#180DaysOfDSA#DailyCodingChallenge #LeetCodeJourney #GeeksforGeeks #CodingNinjas #Codechef #CodeForces #ContinuousLearning #TechCommunity

Finding the Single Number in an Array
In this explanation, we'll look at a Java method that identifies the single number in an array where every other number appears exactly twice. The solution uses the XOR bitwise operation for its efficiency and simplicity.
Problem Statement
Given an array of integers, every element appears twice except for one. We need to find that single one. The solution should have a linear runtime complexity and use only constant extra space.
Approach
We will use the XOR bitwise operation to solve this problem efficiently. Here's why XOR is perfect for this:
Properties of XOR:
XOR of a number with itself is 0:
a ^ a = 0XOR of a number with 0 is the number itself:
a ^ 0 = aXOR is commutative and associative, meaning the order of operations does not matter.
Using these properties, we can XOR all the elements of the array. The pairs of duplicate elements will cancel each other out (resulting in 0), and we will be left with the single number that does not have a duplicate.
Code Explanation
Here’s the code:
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
result = result ^ nums[i];
}
return result;
}
}
Step-by-Step Explanation:
Initialization:
- We start with a variable
resultinitialized to 0.
- We start with a variable
Iterating through the Array:
We iterate through each element of the array using a for loop.
In each iteration, we apply the XOR operation between
resultand the current array elementnums[i].This step ensures that each pair of duplicate numbers cancels out (since
a ^ a = 0).
Final Result:
- After completing the iteration,
resultwill hold the value of the single number that does not have a duplicate.
- After completing the iteration,
Example Walkthrough
Consider the array [4, 1, 2, 1, 2]:
Initial
resultis 0.Iteration 1:
result = 0 ^ 4->result = 4Iteration 2:
result = 4 ^ 1->result = 5Iteration 3:
result = 5 ^ 2->result = 7Iteration 4:
result = 7 ^ 1->result = 6Iteration 5:
result = 6 ^ 2->result = 4
The result after processing all elements is 4, which is the single number in the array.
Conclusion
This method is efficient because it only requires one pass through the array (O(n) time complexity) and uses a constant amount of extra space (O(1) space complexity). By leveraging the properties of the XOR operation, we can easily find the single number that appears only once in the array.