Introduction
The Single Number problem involves finding the element that appears exactly once in an array.
Given an integer array arr[]:
- every element appears twice
- except one element
The task is to find that unique element.
This problem introduces an important bit manipulation concept:
XOR OperationThis problem helps in understanding:
- hashing techniques
- bit manipulation
- XOR properties
- optimized traversal
Example
Input:arr[] = [2,2,1]
Output:
1
Explanation:
2 appears twice
1 appears only once
Input:
arr[] = [4,1,2,1,2]
Output:
4
Explanation:
1 and 2 appear twice
4 appears once
Constraints
1 <= n <= 3 * 10^4-3 * 10^4 <= arr[i] <= 3 * 10^4Every element appears twice except one
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Traverse every element
- Count its frequency
- Return the element having frequency 1
This approach is easy to understand but repeated counting increases time complexity.
Steps
- Traverse array using index i.
- Count frequency of arr[i].
- If frequency becomes 1:
- return element
- Continue traversal otherwise.
Dry Run
Input:arr = [4,1,2,1,2]
Traverse 4:
Frequency = 1
Single number found
Return 4
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:
Nested traversal is used for counting frequencies.
Space Complexity: O(1)
Explanation:
No extra data structures are used.
Approach 2 : Better Solution (Hashing)
Explanation
Instead of repeatedly counting frequencies, we can use hashing.
The idea is:
- Store frequencies in hashmap
- Traverse hashmap
- Return element having frequency 1
This reduces time complexity significantly.
Steps
- Create hashmap.
- Store frequencies.
- Traverse hashmap.
- Return element with frequency 1.
Dry Run
Input:arr = [4,1,2,1,2]
Store frequencies:
4 → 1
1 → 2
2 → 2
Traverse hashmap:
4 has frequency 1
Return 4
Better Code
Complexity Analysis
Time Complexity: O(n)Explanation: Array is traversed once for frequency counting.
Space Complexity: O(n)
Explanation: Extra hashmap is used.
Approach 3 : Optimized Solution (XOR Technique)
Explanation
The optimized solution uses XOR properties:
a ^ a = 0a ^ 0 = aThis means:
- duplicate elements cancel each other
- only single number remains
This provides:
- O(n) time
- O(1) space
Steps
- Initialize answer = 0.
- Traverse array.
- XOR every element with answer.
- Final answer becomes single number.
Dry Run
Input:arr = [4,1,2,1,2]
Initially:
answer = 0
XOR 4:
0 ^ 4 = 4
answer = 4
XOR 1:
4 ^ 1 = 5
answer = 5
XOR 2:
5 ^ 2 = 7
answer = 7
XOR 1:
7 ^ 1 = 6
answer = 6
XOR 2:
6 ^ 2 = 4
Final Result:
4
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation: Each element is processed once.
Space Complexity: O(1)
Explanation:
No extra data structures are used.