Monitoring~25 min2s · 256 MBtarget O(n × m) time, O(m) spaceclassic twin: lc-97dp
Two services in a monitoring system write their log lines to one combined log. Each line is reduced to one letter. The lines of one service stay in the order the service wrote them, but they can be mixed with the lines of the other.
After an outage, the combined log is all that survives. You need to check whether it could have come from the two service logs.
Write is_interleaving(first, second, merged).
first and second are the logs of the two services, lowercase letters.merged is the combined log.true when merged can be made by taking every letter of both logs exactly once, keeping the order within each log. Return false otherwise.Input: first = "ace", second = "bd", merged = "abcde"
Output: trueLet fits[i][j] say whether the first i letters of first and the first j letters of second can make the first i + j letters of merged. With nothing used the answer is yes. Letter i + j of merged came from first, which needs fits[i - 1][j] and a matching letter, or from second, which needs fits[i][j - 1] and a matching letter.
| first \ second | (none) | b | d |
|---|---|---|---|
| (none) | yes | no | no |
| a | yes | yes | no |
| c | no | yes | yes |
| e | no | no | yes |
The last cell is yes. Take a from the first log, b from the second, then c, d and e alternately.
Input: first = "ab", second = "ac", merged = "aabc"
Output: trueTake a from either log, then a from the other, then b and c.
Input: first = "ab", second = "c", merged = "bac"
Output: falseThe letters are the same as in merged, but a must come before b, and merged has b first.
1 ≤ len(first) ≤ 500 and 1 ≤ len(second) ≤ 5001 ≤ len(merged) ≤ 1000The table has 501 × 501 = 251,001 cells, and each takes one step, about a quarter of a million. The number of ways to mix two logs of 500 letters is far larger than any machine can try, because it is a number of 300 digits.