Social feed~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-260bit-manipulation
A social feed stores every post in two data centres, and each centre writes the post id to its own report. The reports are merged, so a normal post id appears twice.
After an outage, two post ids were written by one centre only, and they appear once. An audit job runs on a small machine with very little memory. It must find the two ids that appear once.
Write find_two_lone_posts(posts).
posts is the merged report, in any order. Every id appears twice, except two different ids that appear once.Input: posts = [10, 3, 10, 14, 3, 6, 6, 9]
Output: [9, 14]The xor of the whole report is 7, because every pair cancels and 9 xor 14 is 7. The lowest set bit of 7 is 1. The ids with that bit set go to one group, and the others to the other group.
| Step | What happens | Result |
|---|---|---|
| [1] | Xor of every id | 7 |
| [2] | Lowest set bit of 7 | 1 |
| [3] | Ids with bit 1 set: 3, 3, 9. Xor of the group | 9 |
| [3] | Ids with bit 1 clear: 10, 10, 14, 6, 6. Xor of the group | 14 |
| [4] | Sort the two | [9, 14] |
Input: posts = [4, 7]
Output: [4, 7]There are no pairs, only the two lone ids.
Input: posts = [5, 2, 9, 9]
Output: [2, 5]The answer is in ascending order, whichever way the groups come out.
2 ≤ len(posts) ≤ 100,000, and the length is even0 ≤ posts[i] ≤ 10^9Counting each id by reading the whole report takes about n × n = 10 billion steps, which is far too slow.
Two passes over the report take about 200,000 steps. Each id has at most 30 bits, and a few numbers are enough as memory.