Data Structures & Algorithms Bit Manipulation
💡
Exercise 153

Single Number 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

This is LeetCode #136: Single Number — the perfect introduction to XOR! 🔮

💡 Think of it like this: Everyone in a room has a twin — except ONE person. How do you find the loner? XOR is the magic trick: when you XOR a number with itself, it becomes 0. So twins cancel out, and only the loner remains!

nums = [4, 1, 2, 1, 2] # XOR everything together: # 4 ^ 1 ^ 2 ^ 1 ^ 2 # = 4 ^ (1 ^ 1) ^ (2 ^ 2) ← pairs cancel! # = 4 ^ 0 ^ 0 # = 4 ✓ (the single number!)

XOR Properties (the magic rules):

  • a ^ a = 0 — Any number XOR itself = 0 (cancel out!)
  • a ^ 0 = a — Any number XOR zero = itself
  • XOR is commutative and associative — order doesn't matter

💭 Your turn! Take what you learned above and write the code yourself. Struggling is part of learning! 🧠

Why this works: Since every number except one appears twice, all pairs cancel to 0 via XOR. The remaining number XORs with 0 and stays as itself. Beautiful! 🎨

📋 Instructions
Find the single number that appears only once.
XOR all numbers together! Since a^a=0 and a^0=a, all pairs cancel out, leaving only the single number. One line: result = 0; for n in nums: result ^= n.
⚠️ Try solving it yourself first — you'll learn more!
def singleNumber(nums):
    result = 0
    for num in nums:
        result ^= num   # XOR everything together
    return result       # Only the single number survives!

# Time: O(n), Space: O(1) — can't do better than this!
🧪 Test Cases
Input
singleNumber([4, 1, 2, 1, 2])
Expected
4
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.