Chat app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-136bit-manipulation
A chat app sends every message to two linked devices, and each device writes the message id to its own log. When you merge the two logs, every id should appear twice. One message reached only one device, so its id appears once.
Your team lead asks: "Find the id that has no pair." Ids are 32-bit whole numbers, and some are negative. The merged log can hold 200,001 ids, and the job runs on a small server, so extra memory should stay small.
Write find_single_id(ids).
ids[i] is a message id. The ids come in any order.Input: ids = [4, 9, 4, 7, 9]
Output: 7Start a running value at 0. For each id, replace the running value by the XOR of the two. XOR is ^: it gives 1 in each bit where the two numbers differ.
| Step | Id read | Running value | Why |
|---|---|---|---|
| 1 | 4 | 4 | 0 ^ 4 is 4 |
| 2 | 9 | 13 | 4 is 0100 and 9 is 1001, so the result is 1101 |
| 3 | 4 | 9 | the second 4 cancels the first one |
| 4 | 7 | 14 | 1001 ^ 0111 is 1110 |
| 5 | 9 | 7 | the second 9 cancels the first one |
The running value ends at 7, the id with no pair.
Input: ids = [2147483647, -5, 2147483647]
Output: -5The two copies of 2147483647 cancel to 0, and 0 ^ -5 is -5. Ids can be negative and as large as 2^31 - 1.
Input: ids = [0]
Output: 0One id, logged once. The answer is 0, even though 0 is also the number you start from.
1 ≤ len(ids) ≤ 200,001, and the length is odd.Comparing every id with every other id takes about n² / 2 steps, which is 20 billion for 200,001 ids. That is too slow, so you need one pass over the list. The ids use the whole 32-bit range, so a table with one slot for each possible id would need over 4 billion slots. A map of counts works, but it keeps up to 100,001 entries, and the task asks for little extra memory.