The Two Lone Numbers
Difficulty: Hard · Pattern: Bit Manipulation · Concept: General Coding (DSA) — Core Patterns to Drill
The Lone Number found the one element appearing once when every other element appeared exactly twice — solved by XORing everything together, since duplicate pairs cancel. This variant is genuinely harder: exactly two elements each appear once, and everything else appears twice. Plain XOR of everything now only gives you a ^ b (the two lone numbers XORed together) — not either number individually, since both survive the cancellation.
The trick that separates them: a ^ b is nonzero (since a != b), so it has at least one set bit — and at that specific bit position, a and b must differ (one has a 1 there, the other a 0, since XOR only sets a bit when the two inputs disagree on it). That single differing bit is enough to partition every number in the array into two groups, each group containing exactly one lone number and all the duplicate pairs that share its value at that bit — collapsing back to two independent instances of the original Lone Number problem.
Your task: implement two_lone_numbers(nums), using only XOR and bitwise AND (no dictionary, no set). Return the two lone numbers as a sorted 2-element list.