STRG-P2

Every place, fast

Practice 2 of 6String algorithms11 tests

The problem

Return every place i where text[i:i + len(pat)] == pat, in increasing order. Occurrences may overlap, and there may be very many of them.

find_every("abababac", "ababac")   # [2]
find_every("aaaaa", "aa")           # [0, 1, 2, 3]
find_every("abacabab", "ab")        # [0, 4, 6]

Both strings have lower-case letters, and the pattern has at least one.

Limits

  • The text has up to 1,000,000 letters and the pattern up to 500,000. The big tests have 4 seconds each.
  • One test has 500,001 overlapping occurrences of a pattern of 500,000 letters. A loop that calls find again after each hit, or compares a slice at every place, does about 250 billion steps there.

Builds on STRG-2 KMP.

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.

11 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Overlapping placesNot run
3Matches that share lettersNot run
4A short patternNot run
5One letterNot run
6Pattern longer than the textNot run
7The same lengthNot run
8No matchNot run
9Half a million in a rowNot run
10Every second placeNot run
11Half a million random lettersNot run