Algorithms and Data Structures · Middle · Question 63 of 75

Every number in an array appears twice except one. How do you find it in O(n) time and O(1) memory?

Explanation

a ^ a = 0 and a ^ 0 = a, and XOR is commutative, so pairs vanish in any order. Sorting is O(n log n); a map is O(n) time but O(n) memory.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 63

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz