Engineering platform~30 min2s · 256 MBtarget O(N log k) time, O(k) spacek-way-merge · heaps
A software platform writes its audit log to several shards. Each shard keeps its events in increasing order of sequence number. An event is replicated to more than one shard, so that the log survives a failed shard.
An event is confirmed when at least quorum shards hold it. The compliance team wants the confirmed events in order, without sorting everything again. The shards may be long.
Write confirmed_events(shards, quorum).
shards[s] is the list of event sequence numbers on shard s, in strictly increasing order. A shard never holds the same number twice.quorum different shards.quorum is larger than the number of shards, the result is empty.Input: shards = [[1, 3, 5, 8], [1, 2, 3, 8, 9], [3, 4, 8, 10]], quorum = 2
Output: [1, 3, 8]The trace keeps the next unread event of each shard in a heap. Each step takes the smallest value, and counts the shards that hold it.
| Step | Smallest event | Shards that hold it | Count | Confirmed? |
|---|---|---|---|---|
| 1 | 1 | shard 0 and shard 1 | 2 | yes |
| 2 | 2 | shard 1 | 1 | no |
| 3 | 3 | shards 0, 1 and 2 | 3 | yes |
| 4 | 4 | shard 2 | 1 | no |
| 5 | 5 | shard 0 | 1 | no |
| 6 | 8 | shards 0, 1 and 2 | 3 | yes |
| 7 | 9 | shard 1 | 1 | no |
| 8 | 10 | shard 2 | 1 | no |
The output is [1, 3, 8].
Input: shards = [[2, 4], [2, 5], [2, 4, 6]], quorum = 3
Output: [2]Only event 2 is on all three shards.
Input: shards = [[1, 2], [3, 4]], quorum = 3
Output: []Quorum 3 is larger than the 2 shards, so no event can be confirmed.
1 ≤ shards.length ≤ 200 (shards); each shard has between 1 and 1,000 events1 ≤ shards[s][i] ≤ 1,000,000,000 (sequence numbers), strictly increasing within a shard1 ≤ quorum ≤ 200There are up to 200,000 events in all. Checking each distinct event against every shard by scanning costs about 200,000 × 200 × 1,000 steps. Sorting everything costs N log N for N events, but it throws away that each shard is already sorted. A heap that holds one event per shard merges them in N log k steps, where k is the number of shards.