Single Number
Every element appears twice except one. Find the single element in O(n) time and O(1) space using XOR.
Sample input
[4, 1, 2, 1, 2]
Sample output
4
Solution
from functools import reduce
nums = [4, 1, 2, 1, 2]
print(reduce(lambda a, b: a ^ b, nums))
const nums = [4, 1, 2, 1, 2];
console.log(nums.reduce((a, b) => a ^ b, 0));
public class Main {
public static void main(String[] args) {
int[] nums = {4, 1, 2, 1, 2};
int result = 0;
for (int num : nums) result ^= num;
System.out.println(result);
}
}
fun main() {
val nums = intArrayOf(4, 1, 2, 1, 2)
println(nums.reduce { a, b -> a xor b })
}
let nums = [4, 1, 2, 1, 2]
print(nums.reduce(0, ^))
void main() {
final nums = [4, 1, 2, 1, 2];
print(nums.reduce((a, b) => a ^ b));
}
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {4, 1, 2, 1, 2};
int result = 0;
for (int num : nums) result ^= num;
cout << result << endl;
return 0;
}
#include <stdio.h>
int main() {
int nums[] = {4, 1, 2, 1, 2};
int n = 5, result = 0;
for (int i = 0; i < n; i++) result ^= nums[i];
printf("%d\n", result);
return 0;
}