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
- 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 | banana | Not run | |
| 2 | No repeat | Not run | |
| 3 | One letter | Not run | |
| 4 | A run | Not run | |
| 5 | mississippi | Not run | |
| 6 | Two of the same length | Not run | |
| 7 | The earlier copy wins | Not run | |
| 8 | 50,000 random letters | Not run | |
| 9 | A copy planted far apart | Not run | |
| 10 | Nearly all of it | Not run | |
| 11 | One half written twice | Not run | |
| 12 | Thue–Morse | Not run |