136. Single Number
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the single element in an array that appears only once, while all other elements appear exactly twice. The key constraints are that the solution must have a linear runtime complexity (O(n)) and use only constant extra space (O(1)). A common approach for finding unique elements, such as using a hash map to count frequencies, would violate the constant space constraint, as it could require up to O(n) space. This suggests we need a more clever approach, likely involving bit manipulation.
Solution
Single Number in Python
class Solution:
def singleNumber(self, nums: List[int]) -> int:
# Initialize the unique number candidate to 0.
# XORing with 0 doesn't change the number (a ^ 0 = a).
single_num = 0
# Iterate through all numbers in the input list.
for num in nums:
# Apply the XOR operation.
# If a number appears twice, it will be XORed with itself,
# resulting in 0 (e.g., x ^ y ^ x = (x ^ x) ^ y = 0 ^ y = y).
# The final result will be the number that appears only once.
single_num ^= num
return single_num
Single Number in Java
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
// Iterate through each number in the array.
for (int num : nums) {
// The XOR operation (^) has the following properties:
// 1. A number XORed with itself is 0 (a ^ a = 0).
// 2. A number XORed with 0 is the number itself (a ^ 0 = a).
// When we XOR all numbers in the array, every number that appears twice
// will cancel itself out, leaving only the unique number.
result ^= num;
}
return result;
}
}
Single Number in C++
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = 0;
// Iterate through each number in the array.
for (int num : nums) {
// The XOR operation has the property that a ^ a = 0 and a ^ 0 = a.
// By XORing all numbers, pairs of identical numbers will cancel out (become 0),
// leaving only the single number that appears once.
result ^= num;
}
return result;
}
};
Single Number in TypeScript
function singleNumber(nums: number[]): number {
let result = 0;
// Iterate through each number in the array.
for (const num of nums) {
// The core of the solution is the XOR bitwise operator.
// Key properties:
// 1. x ^ x = 0 (a number XORed with itself is zero)
// 2. x ^ 0 = x (a number XORed with zero is itself)
// 3. XOR is commutative and associative.
//
// By XORing all elements, pairs of identical numbers cancel out,
// leaving only the number that appears once.
result ^= num;
}
return result;
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.