The problem
For every place i of the text, find how much of the pattern fits there: the largest k such that text[i:i + k] == pat[:k]. Return these numbers as a list, one per place of the text. An answer is 0 when the first letters differ, and can never be more than the letters left in the text.
fits("aabxaab", "aab") # [3, 1, 0, 0, 3, 1, 0]
fits("xxaba", "abab") # [0, 0, 3, 0, 1]
fits("ab", "abab") # [2, 0]
Both strings have lower-case letters, and the pattern has at least one.
Limits
- The text has up to 500,000 letters and the pattern up to 100,000. The big tests have 3 seconds each.
- Comparing letter by letter at every place is too slow when the answers are long.
Builds on STRG-3 Z-algorithm.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Starts of a longer pattern | Not run | |
| 3 | Runs off the end | Not run | |
| 4 | Pattern longer than the text | Not run | |
| 5 | One letter | Not run | |
| 6 | Nothing fits | Not run | |
| 7 | Long runs | Not run | |
| 8 | A periodic text | Not run | |
| 9 | Random letters | Not run |