AlgoMaster Logo

Single Number

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

In a brute force approach, for each element in the array, we can check if it appears again in the array. We can do this by comparing each element against all others. The element that doesn't have a duplicate is the single number.

Code:

2. HashMap

Intuition:

Utilize a HashMap to count the occurrences of each element. Then, iterate over the HashMap to find the element with a count of one, which is our single number.

Code:

3. Bit Manipulation

Intuition:

The most optimal solution involves using the XOR operation.

XOR has three important properties:

  1. x ⊕ x = 0: A number XOR'ed with itself cancels out.
  2. x ⊕ 0 = x: XOR with zero leaves the number unchanged.
  3. XOR is commutative and associative: (a ⊕ b) ⊕ c = a ⊕ (b ⊕ c)

Putting these together:

When we XOR all elements in the array, every duplicate pair cancels out to 0, and only the unique element survives.

Example Walkthrough:

0
4
1
1
2
2
3
1
4
2
result = 0
Step 1 / 6