Skip to content

260. Single Number III #115

Answered by mah-shamim
mah-shamim asked this question in Q&A
Jul 27, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

We can use bit manipulation, specifically the XOR operation. The key idea is that XORing two identical numbers results in 0, and XORing a number with 0 gives the number itself. Using this property, we can find the two unique numbers that appear only once in the array.

Step-by-Step Solution:

  1. XOR all elements in the array. The result will be the XOR of the two unique numbers because all other numbers will cancel out (since they appear twice).

  2. Find a set bit in the XOR result (this bit will be different between the two unique numbers). You can isolate the rightmost set bit using xor & (-xor).

  3. Partition the array into two groups based on the set bit. XOR all numbers in each group to fin…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Aug 23, 2024
Collaborator

@mah-shamim
Comment options

mah-shamim Aug 23, 2024
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants