Chat app~35 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1392string-algorithms
A chat app saves a conversation as an archive of message codes, one letter for each message. A signature block is a run of codes that opens the archive and also closes it.
The app wants to compress a block that is repeated three times: at the start, at the end, and somewhere strictly in between. Your team lead asks: "How long is the longest block that opens the archive, closes it, and appears in the middle as well?"
Write longest_framed_block(archive).
archive is the saved conversation, one letter for each message.s with 1 ≤ s and s + len(block) < len(archive), so that it is neither the opening block nor the closing block.Input: archive = "abcaabcbabc"
Output: 3The longest block that opens and closes the archive is abc. It appears again at position 4, strictly between the ends, so the answer is 3. The table shows pi[i], the length of the longest proper prefix of archive[0..i] that is also its ending.
| i | Letter | pi[i] | Meaning |
|---|---|---|---|
| 0 | a | 0 | no border |
| 1 | b | 0 | no border |
| 2 | c | 0 | no border |
| 3 | a | 1 | a opens and closes abca |
| 4 | a | 1 | a opens and closes abcaa |
| 5 | b | 2 | ab opens and closes abcaab |
| 6 | c | 3 | abc opens and closes abcaabc |
| 7 | b | 0 | no border |
| 8 | a | 1 | a opens and closes abcaabcba |
| 9 | b | 2 | ab opens and closes abcaabcbab |
| 10 | c | 3 | abc opens and closes abcaabcbabc |
Input: archive = "abcabc"
Output: 0The block abc opens and closes the archive, but the only room strictly inside is the letters bca and cab, so it does not recur. No shorter block opens and closes it either.
Input: archive = "aaaa"
Output: 2The longest border is aaa, but it cannot fit strictly inside. The block aa opens, closes, and starts at position 1, which is strictly inside.
1 ≤ len(archive) ≤ 200,000archive uses only the letters a, b and c.Testing each length from the top by comparing letters costs up to about 4,999,900,000 steps when many lengths almost match. A table of borders, built in one pass, gives all the lengths that open and close the archive. That costs about 399,998 steps.