In this array, every number turns up twice except one. In [2, 2, 1] the odd one out is 1; in [4, 1, 2, 1, 2] it’s 4. The challenge is to find it in one linear pass without setting aside extra storage.
My first thought was to ask Python how often each number occurs:
1 | for i in nums: |
That looks like a single loop until you remember what count has to do. Each call searches the list again.
Next I tried sorting the numbers so the pairs would sit side by side. I kept two integers, one for the value I was watching and one for the count:
1 | def func(nums): |
That actually passed: 88 ms, faster than 22.81% of submissions, and 14.8 MB, ahead of 48.18% on memory. I’ll take the green check mark, but sorting had already blown the linear-time budget.
I went back to the solutions. A hash table sounded familiar from discrete math. In my head I pictured [3,1,2,4,5] and putting 3 in a slot labeled 3 so I could go straight back to it. A Python dictionary would let me count occurrences along those lines, at the cost of extra storage.
The answer I wish I’d thought of was XOR. Two copies of the same value XOR to zero. And since XOR is commutative, those copies don’t even have to be next to each other: every pair cancels somewhere along the way. Just one value survives. How neat is that?
1 | def func(nums): |




