STRG-P3

How much of the pattern fits

Practice 3 of 6String algorithms9 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Starts of a longer patternNot run
3Runs off the endNot run
4Pattern longer than the textNot run
5One letterNot run
6Nothing fitsNot run
7Long runsNot run
8A periodic textNot run
9Random lettersNot run