Monitoring~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-137bit-manipulation
A service is watched by three redundant monitors. When something breaks, each monitor raises an alert with the same id, so a normal alert appears three times in the merged feed.
One day, two of the monitors were down for a short time. One alert was raised by one monitor only, and it appears once. The collector runs on a small device and cannot keep a table of counts. Find the id of the alert that appears once.
Write find_lone_alert(alerts).
alerts is the merged feed, in any order. Every id appears three times, except one id that appears once.Input: alerts = [20, 12, 20, 12, 12, 20, 3]
Output: 3Keep two numbers, ones and twos. A bit of ones is set when that bit has been seen once more than a multiple of three times. A bit of twos is set when it has been seen twice more.
| After the id | ones |
twos |
|---|---|---|
| 20 | 20 | 0 |
| 12 | 24 | 4 |
| 20 | 8 | 16 |
| 12 | 4 | 24 |
| 12 | 0 | 20 |
| 20 | 0 | 0 |
| 3 | 3 | 0 |
After the three 12s and the three 20s both numbers are zero, and only the lone id 3 is left in ones.
Input: alerts = [7]
Output: 7Only the lone alert is in the feed.
Input: alerts = [0, 0, 0, 5]
Output: 5The repeated id may be 0. It sets no bits, so it leaves no trace.
1 ≤ len(alerts) ≤ 300,001, and the length is one more than a multiple of 30 ≤ alerts[i] ≤ 10^9Counting each id by reading the whole feed takes about n × n = 90 billion steps. That is far too slow.
One pass takes 300,001 steps. An id below 10^9 has at most 30 bits, so keeping a count for each bit takes constant memory too.