STRG-P4

The longest repeated piece

Practice 4 of 6String algorithms12 tests

The problem

Return the longest piece (a run of neighbouring letters) of s that occurs at two or more places. The two copies may overlap. If several different pieces have that length, return the one whose first occurrence is earliest in s: in "cdqcdabqab" both "cd" and "ab" repeat, and "cd" is seen first. If no piece repeats at all, return "".

longest_repeat("banana")       # "ana"
longest_repeat("aaaa")         # "aaa"
longest_repeat("cdqcdabqab")   # "cd"
longest_repeat("abcd")         # ""

The string has lower-case letters. If you use a rolling hash, use a large prime modulus such as (1 << 61) - 1, and compare the letters when two hashes are equal: one test is built to make weak hashes give the same value for different pieces.

Limits

  • Up to 100,000 letters. The big tests have 4 to 5 seconds each.
  • The answer can be almost as long as the string, so building a slice for every piece of every length you try is too slow.

Builds on STRG-4 Rolling hash and Rabin-Karp.

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.

12 tests, not run yet
Test results
#TestResultReads · time
1bananaNot run
2No repeatNot run
3One letterNot run
4A runNot run
5mississippiNot run
6Two of the same lengthNot run
7The earlier copy winsNot run
850,000 random lettersNot run
9A copy planted far apartNot run
10Nearly all of itNot run
11One half written twiceNot run
12Thue–MorseNot run