Monitoring~20 min2s · 256 MBtarget O(n + m) time, O(m) spacestring-algorithms
A monitoring screen shows an event log with one letter for each minute. Each letter is a type of event, such as a for a slow reply or b for a failed check.
An alarm code is a short pattern of letters. The on-call team wants every minute where the code starts in the log, including starts that overlap. Your team lead asks: "List every start position of the code in the log."
Write alarm_positions(log, code).
log is the event log, one letter for each minute. The first minute has position 0.code is the alarm code.code starts inside log, in increasing order. Two matches may overlap.code is longer than log.Input: log = "abababa", code = "aba"
Output: [0, 2, 4]The code aba appears three times, and each match shares a letter with the next. The scan keeps k, the number of code letters that match the end of the log read so far. After a full match, k falls back to the longest prefix of the code that is also its ending, which is 1 letter here (a).
| i | Letter | k before | k after | Result |
|---|---|---|---|---|
| 0 | a | 0 | 1 | no match yet |
| 1 | b | 1 | 2 | no match yet |
| 2 | a | 2 | 3 | match, start 0 |
| 3 | b | 1 | 2 | no match yet |
| 4 | a | 2 | 3 | match, start 2 |
| 5 | b | 1 | 2 | no match yet |
| 6 | a | 2 | 3 | match, start 4 |
Input: log = "abc", code = "abca"
Output: []Only a code that fits the log can match, and here the code is longer than the log.
Input: log = "aaaa", code = "aa"
Output: [0, 1, 2]Overlapping starts count: in aaaa the code aa starts at 0, 1 and 2.
1 ≤ len(log) ≤ 200,0001 ≤ len(code) ≤ 1,000a, b and c.Comparing the code at every start costs up to 200,000 × 1,000 = 200,000,000 letter comparisons. A log of a and a code that ends in b fails only at the last letter each time. Reading each log letter once, with a fallback table, costs about 201,000 steps.