WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Coding Interview Essentials Β· Bit Manipulation Problems Β· question 84 of 120

Can you find the only non-repeating number in an array where every element repeats twice except one, using bit manipulation?

πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

We can find the non-repeating number in an array where every other element repeats twice using bit manipulation. This can be achieved using the XOR bitwise operator.

The XOR operation ("exclusive or") is a binary operation that takes two bits and returns 1 if exactly one of the bits is 1. In other words, it returns true if the two bits are opposite.

The XOR operation has two properties which are very useful in this context:

1) β€˜A XOR A = 0β€˜

2) β€˜A XOR 0 = Aβ€˜

3) β€˜A XOR B XOR A = Bβ€˜

If we XOR all elements in the array, all the elements which are repeated twice will become 0 (because β€˜A XOR A = 0β€˜), and we are left with the element which is only present once as the result.

Suppose we have an array β€˜arr[] = 2, 3, 5, 4, 5, 3, 4β€˜.

If we XOR all the numbers together:

β€˜(2 3Μ‚ 5Μ‚ 4Μ‚ 5Μ‚ 3Μ‚ 4Μ‚)β€˜

We can reorder as:

β€˜((2 2Μ‚) (Μ‚3 3Μ‚) (Μ‚4 4Μ‚) (Μ‚5 5Μ‚)) 5Μ‚β€˜

Each pair of the same number will XOR to 0, leaving us with:

β€˜0 5Μ‚β€˜

Remember β€˜A XOR 0 = Aβ€˜, therefore we get β€˜5β€˜ which is the number that has no duplicate in the array.

A Python example code:

def find_single(nums):
    res = 0
    for num in nums:
        res ^= num
    return res

For an array β€˜arr[] = 2, 3, 5, 4, 5, 3, 4β€˜, calling β€˜find_single(arr)β€˜ would return β€˜5β€˜.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview β€” then scores it.
πŸ“ž Practice Coding Interview Essentials β€” free 15 min
πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

All 120 Coding Interview Essentials questions Β· All topics