Single Number
Easy bit-manipulation
Description
Constraints
1 <= n <= 100000
Examples
Input: nums = [4,1,2,1,2]
Output: 4
Hints (1)
- XOR of a number with itself is zero, and XOR is commutative.
Solutions
XOR all values. · Time O(n) · Space O(1)
func singleNumber(nums []int) int {
x := 0
for _, n := range nums {
x ^= n
}
return x
}
XOR all values. · Time O(n) · Space O(1)
function singleNumber(nums) {
return nums.reduce((a, b) => a ^ b, 0);
}
XOR all values. · Time O(n) · Space O(1)
function singleNumber($nums) {
$x = 0;
foreach ($nums as $n) { $x ^= $n; }
return $x;
}
XOR all values. · Time O(n) · Space O(1)
def singleNumber(nums):
x = 0
for n in nums:
x ^= n
return x
XOR all values. · Time O(n) · Space O(1)
function singleNumber(nums: number[]): number {
return nums.reduce((a, b) => a ^ b, 0);
}
Create a free account to submit solutions, track progress and save problems.
Create account