#136EasyBit Manipulation

Single Number

XOR cancels duplicates — the cleverest single-line solution in DSA.

AmazonBloombergGoogleApple

Problem Statement

Given a non-empty array nums where every element appears twice except for one, find that single one. You must implement a solution with linear runtime complexity and use only constant extra space.

Examples

Example 1

Input:nums = [2,2,1]
Output:1

Example 2

Input:nums = [4,1,2,1,2]
Output:4

Constraints

  • 1 ≤ nums.length ≤ 3 × 10⁴
  • -3 × 10⁴ ≤ nums[i] ≤ 3 × 10⁴
  • Each element appears twice except for one.

Solutions

1
Hash Map to Count Occurrences
TimeO(n)SpaceO(n)

Count occurrences of each number using a hash map. Return the number whose count is 1. Uses O(n) extra space.

Visual Animation
def singleNumber(nums: list[int]) -> int:
    counts = {}
    for num in nums:
        counts[num] = counts.get(num, 0) + 1
    return next(k for k, v in counts.items() if v == 1)

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Bit Manipulation to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems