Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Every number in a list of sensor IDs appears twice except one. Find the lonely ID in O(n) time and O(1) space.

Problem: Every number in a list of sensor IDs appears twice except one. Find the lonely ID in O(n) time and O(1) space.
def lonely(a):
    r = 0
    for x in a:
        r ^= x
    return r
print(lonely([14, 7, 9, 14, 3, 9, 7]))
What is printed?
  1. A. 14
  2. B. 0
  3. C. 3
  4. D. 7

Correct answer: C. 3

XOR is associative and x ^ x = 0, so every paired value cancels and only 3 survives. O(n) time, O(1) space; a hash-count solution also works but needs O(n) space.

More Coding Interview Problems questions

Exams that ask this topic