Skip to content

Single Number

Given a non-empty array of integers where every element appears twice except for one, find that single element.

You need to solve this problem efficiently.

InputOutputExplanation
Example 1Result 1Explanation for example 1
Example 2Result 2Explanation for example 2
  • Constraint 1 for Single Number
  • Constraint 2
  • Constraint 3
ApproachTimeSpaceBest When
XorO(n)O(1)When applicable
HashmapO(n)O(1)When applicable
MathO(n)O(1)When applicable
★ Recommended

This approach provides an efficient solution for single number.

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
single_number_xor.py
from typing import List
def single_number_xor(nums: List[int]) -> int:
"""Find single number using XOR operation."""
result = 0
for num in nums:
result ^= num
return result
# Test cases
print(single_number_xor([2, 2, 1])) # 1
print(single_number_xor([4, 1, 2, 1, 2])) # 4
🎯 Interview Favourite

This approach provides an efficient solution for single number.

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
single_number_hashmap.py
# Python Solution
# Problem: single-number
# Approach: hashmap
# Implementation placeholder for single_number_hashmap
# This file is auto-generated and should contain the solution code.
def single_number_hashmap():
pass
if __name__ == "__main__":
pass
✓ Simple

This approach provides an efficient solution for single number.

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
single_number_math.py
# Python Solution
# Problem: single-number
# Approach: math
# Implementation placeholder for single_number_math
# This file is auto-generated and should contain the solution code.
def single_number_math():
pass
if __name__ == "__main__":
pass