Short answer
Both solutions are O(n) in time, so algorithmically they’re tied. In practice the Counter version can even look faster because most of the heavy lifting is done in C, whereas your XOR loop runs entirely in Python byte-code.
Long(er) answer
-
Big-O parity
• XOR version: one pass → O(n) time, O(1) extra memory
• Counter version: one pass to count + up to k (distinct numbers) look-ups → O(n) time, O(k) memory
If the input size is ≤ 30 000 (LeetCode constraint), both finish in a few 10-ths of a millisecond—so the judge’s timer can’t easily distinguish them.
-
Constant-factor reality in CPython
XOR loop
ans = 0
for x in nums: # <-- Python for-loop (byte-code)
ans ^= x # <-- Python int xor (byte-code)
Every iteration has to
• fetch x as a Python object
• execute a Python-level op (BINARY_XOR)
• assign back to ans
That’s ~8-10 byte-code instructions per element.
Counter loop
nums_ct = Counter(nums)
That single line calls collections._count_elements, a C function that
• iterates over the list in C
• increments a C dictionary entry
…so the per-element cost is native (no Python byte-code per item).
After that you only loop over the distinct keys, usually far fewer than n.
Result: despite the extra hash table, the constant factors are smaller, so wall-clock time can tie or beat the pure-Python XOR loop.
-
Noise in LeetCode timings
• They run CPython with a warm interpreter but cold caches.
• Test cases are modest; tiny fluctuations (CPU scheduling, GC, cache misses) easily swamp a few microseconds of real difference.
• The web UI reports the percentile of the particular run, not an average over many runs, so “faster” can just be measurement noise.
-
Trade-offs to remember
• Memory: XOR → O(1) extra; Counter → one dict (≈ 8–10 bytes per distinct key).
• Generality: XOR trick only works when “every element appears exactly twice except one.” Counter works for “appears k times except one”, “find all non-duplicates”, etc.
• Readability: some interviewers love the XOR idiom; others prefer the more obvious counting approach.
Take-away
Your Counter solution feels just as fast because, under Python’s hood, most of it runs in C, whereas the “clever” XOR is still interpreted Python for every element. In languages with compiled loops (C++, Java) the XOR version would usually win; in CPython they’re neck-and-neck unless you hit huge data sizes where the extra memory hurts.