Skip to content

Commit 765cf6b

Browse files
Solution #137 - Kailash Senthilkumar - 09/08/2025
1 parent 11cc0de commit 765cf6b

File tree

8 files changed

+170
-0
lines changed

8 files changed

+170
-0
lines changed
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
# Single Number II
2+
3+
**Difficulty:** Medium
4+
**Category:** Arrays, Bit Manipulation
5+
**Leetcode Link:** [Problem Link](https://leetcode.com/problems/single-number-ii/)
6+
7+
---
8+
9+
## 📝 Introduction
10+
11+
We are given an integer array `nums` where every element appears exactly **three times**, except for one element which appears exactly **once**. The task is to find and return this unique element.
12+
The solution must have:
13+
- **Linear runtime complexity** O(n)
14+
- **Constant extra space** O(1)
15+
16+
---
17+
18+
## 💡 Approach & Key Insights
19+
20+
The naive approach would involve counting the occurrences of each number (using a hash map), but that would require **O(n)** extra space, violating the space constraint.
21+
22+
Instead, we can use **bitwise manipulation** to track the count of each bit across all numbers:
23+
- Maintain two bitmasks:
24+
- **`ones`** → bits that have appeared exactly once so far.
25+
- **`twos`** → bits that have appeared exactly twice so far.
26+
- When a bit appears a **third time**, it is removed from both `ones` and `twos`.
27+
28+
The key insight:
29+
- `ones = (ones ^ num) & ~twos`
30+
- `twos = (twos ^ num) & ~ones`
31+
- XOR toggles the bit, AND with `~` masks out unwanted bits.
32+
33+
---
34+
35+
## 🛠️ Breakdown of Approaches
36+
37+
### 1️⃣ Brute Force / Naive Approach
38+
39+
- **Explanation:**
40+
Use a hash map to count each number’s frequency, then return the number with count = 1.
41+
- **Time Complexity:** O(n)
42+
- **Space Complexity:** O(n)
43+
44+
Example:
45+
`nums = [2, 2, 3, 2]` → Frequency: `{2: 3, 3: 1}` → Output: `3`
46+
47+
---
48+
49+
### 2️⃣ Bitwise Counting Approach
50+
51+
- **Explanation:**
52+
For each bit position (0–31), count how many numbers have that bit set.
53+
Take `count % 3` to determine if that bit belongs to the unique number.
54+
- **Time Complexity:** O(32n) ≈ O(n)
55+
- **Space Complexity:** O(1)
56+
57+
Example:
58+
Count bits column-wise → reconstruct the number.
59+
60+
---
61+
62+
### 3️⃣ Best / Final Optimized Approach (Bitmask Method)
63+
64+
- **Explanation:**
65+
Use `ones` and `twos` to track the counts of bits modulo 3.
66+
- **Time Complexity:** O(n) — single pass
67+
- **Space Complexity:** O(1) — only two variables used
68+
69+
Example/Dry Run for `nums = [2, 2, 3, 2]`:
70+
Binary:
71+
- 2 → `10`
72+
- 3 → `11`
73+
74+
Step-by-step:
75+
```
76+
Initial: ones=00, twos=00
77+
78+
num=2: ones=(00^10)&~00=10, twos=(00^10)&~10=00
79+
num=2: ones=(10^10)&~00=00, twos=(00^10)&~00=10
80+
num=3: ones=(00^11)&~10=01, twos=(10^11)&~01=00
81+
num=2: ones=(01^10)&~00=11, twos=(00^10)&~11=00
82+
Final: ones=11 (decimal 3)
83+
```
84+
Output: `3`
85+
86+
---
87+
88+
## 📊 Complexity Analysis
89+
90+
| Approach | Time Complexity | Space Complexity |
91+
| ------------- | --------------- | ---------------- |
92+
| Brute Force | O(n) | O(n) |
93+
| Bit Count | O(n) | O(1) |
94+
| Bitmask Method| O(n) | O(1) |
95+
96+
---
97+
98+
## 📉 Optimization Ideas
99+
100+
The **bitmask method** is already optimal for both runtime and space. Any further improvements would be micro-optimizations or hardware-specific.
101+
102+
---
103+
104+
## 📌 Example Walkthroughs & Dry Runs
105+
106+
Example:
107+
```
108+
Input: nums = [0, 1, 0, 1, 0, 1, 99]
109+
Output: 99
110+
111+
Step-by-step bitmask evolution:
112+
ones=0, twos=0
113+
Process each number using:
114+
ones = (ones ^ num) & ~twos
115+
twos = (twos ^ num) & ~ones
116+
Final ones=99 → Output
117+
```
118+
119+
---
120+
121+
## 🔗 Additional Resources
122+
123+
- [LeetCode Bit Manipulation Patterns](https://leetcode.com/tag/bit-manipulation/)
124+
- [GeeksforGeeks - Bitwise Operators](https://www.geeksforgeeks.org/bitwise-operators-in-c-cpp/)
125+
126+
---
127+
128+
Author: Kailash Senthilkumar
129+
Date: 09/08/2025
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
public:
3+
int singleNumber(vector<int>& nums) {
4+
int ones = 0, twos = 0;
5+
for (int num : nums) {
6+
// Update 'ones' with bits appearing first time or third time
7+
ones = (ones ^ num) & ~twos;
8+
// Update 'twos' with bits appearing second time
9+
twos = (twos ^ num) & ~ones;
10+
}
11+
// 'ones' will contain the number that appears only once
12+
return ones;
13+
}
14+
};
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public int singleNumber(int[] nums) {
3+
int ones = 0;
4+
int twos = 0;
5+
for(int num:nums){
6+
// This updates 'ones' with bits appearing first time or third time
7+
ones = (ones^num) & ~twos;
8+
// This updates 'twos' with bits appearing second time
9+
twos =(twos^num) & ~ones;
10+
11+
12+
13+
}
14+
// The 'ones' variable will contain the number that has appeared only once.
15+
return ones;
16+
}
17+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution:
2+
def singleNumber(self, nums):
3+
ones, twos = 0, 0
4+
for num in nums:
5+
# Update 'ones' with bits appearing first time or third time
6+
ones = (ones ^ num) & ~twos
7+
# Update 'twos' with bits appearing second time
8+
twos = (twos ^ num) & ~ones
9+
# 'ones' will contain the number that appears only once
10+
return ones
File renamed without changes.

0 commit comments

Comments
 (0)