Search~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-268bit-manipulation
A search service splits its index into shards. A shard should hold every document id from lo to hi. A bug dropped exactly one id. The ids that remain are stored in no particular order.
The on-call team wants to find the dropped id without sorting the shard or building a large table. Your team lead asks: "Which id is missing?"
Write missing_document(ids, lo, hi).
ids is the list of ids in the shard. All are different, and they are in no particular order.lo to hi. Exactly one of them is missing, so len(ids) equals hi - lo.Input: ids = [7, 9, 13, 10, 8, 12], lo = 7, hi = 13
Output: 11The XOR of every id from 7 to 13 is 6. XOR the ids that are present, one at a time, and the XOR of the full range cancels every id except the missing one.
| Id read | XOR so far |
|---|---|
| 7 | 7 |
| 9 | 14 |
| 13 | 3 |
| 10 | 9 |
| 8 | 1 |
| 12 | 13 |
The XOR of the present ids is 13. Combining it with 6 gives 6 ^ 13 = 11, which is the missing id.
Input: ids = [1], lo = 1, hi = 2
Output: 2The shard should hold 1 and 2, and only 1 is there.
Input: ids = [0, 1, 3], lo = 0, hi = 3
Output: 2The range starts at 0, so there is no part below lo to remove, and the missing id is 2.
1 ≤ len(ids) ≤ 700,0000 ≤ lo ≤ hi ≤ 1,000,000,000len(ids) = hi - lo, and ids holds different numbers from lo to hi.Looking for each id of the range in the list costs about n × n / 2 steps, which is about 245,000,000,000 for 700,000 ids. Sorting works, but it costs more than one pass. The XOR of the ids from lo to hi needs no pass at all, because it repeats every 4 numbers. One pass over the list then costs about 700,000 steps.