136. Single Number
Asked at 17Bloomberg65Amazon59Google58Microsoft52Meta51Apple22Amdocs73tcs72Huawei67Airbnb66Qualcomm58Cognizant57Adobe55Accenture44Infosys30Salesforce28Goldman Sachs21
Problem
Every value in nums appears twice except one, which appears once. Return that one, in O(n) time and O(1) extra space.
Example: [4,1,2,1,2] → 4
XOR everything: pairs cancel, the single number remains.
Complexity: O(n) time, O(1) space.
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(lambda a, b: a ^ b, nums)
assert Solution().singleNumber([4, 1, 2, 1, 2]) == 4
assert Solution().singleNumber([2, 2, 1]) == 1
assert Solution().singleNumber([1]) == 1
class Solution {
public int singleNumber(int[] nums) {
int x = 0;
for (int v : nums) x ^= v;
return x;
}
}
func singleNumber(nums []int) int {
x := 0
for _, v := range nums { // pairs cancel: a ^ a = 0
x ^= v
}
return x
}