-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingle-number-ii.js
More file actions
37 lines (30 loc) · 831 Bytes
/
single-number-ii.js
File metadata and controls
37 lines (30 loc) · 831 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Problem: Single Number II
* Link: https://leetcode.com/problems/single-number-ii/
* Difficulty: Medium
*
* Every element appears three times except one. Find the single one.
*
* Time Complexity: O(n)
* Space Complexity: O(1)
*/
// JavaScript Solution - Bit manipulation with ones/twos
function singleNumber(nums) {
let ones = 0, twos = 0;
for (const num of nums) {
// 'ones' holds bits that appeared exactly 1 time
// 'twos' holds bits that appeared exactly 2 times
ones = (ones ^ num) & ~twos;
twos = (twos ^ num) & ~ones;
}
return ones; // bits that appeared exactly once
}
module.exports = singleNumber;
/* Python Solution:
def singleNumber(nums):
ones, twos = 0, 0
for num in nums:
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
return ones
*/