AlgoMaster Logo

Single Number III

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. HashMap

Intuition:

The simplest approach to solve this problem is to use a HashMap to count the occurrences of each number in the array. We then find the two numbers that appear exactly once by iterating through the map.

Code:

2. Bit Manipulation

Intuition:

A more optimal solution uses bit manipulation. First, XOR all numbers to find the XOR of the two unique numbers. Then, find a bit that is set (1) in the XOR result and use it to differentiate the two unique numbers.

Steps:

  • XOR operation between two identical numbers will cancel each other out to 0.
  • By XORing all numbers, every pair of identical numbers cancels out, leaving us with the XOR of the two unique numbers.
  • A single set bit in the XOR result tells us which bit differentiates the two unique numbers.
  • We can use this bit to separate numbers into two groups and find the two unique numbers by XORing within these groups.

Code: