progress

~/problems / String hashing

Longest repeated substring

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

hard ~40 min

Write longest_dup_substring(s) -> str returning a longest substring that appears at least twice in s (the two occurrences may overlap). If several different substrings share the maximum length, return any of them. If no substring repeats, return "".

longest_dup_substring("mississippi")   # "issi"  (at positions 1 and 4, overlapping)
longest_dup_substring("abcd")          # ""
longest_dup_substring("zzzz")          # "zzz"

Constraints: 2 <= len(s) <= 3 * 10**4, lowercase letters.

⭐ Bonus: trying lengths one by one, or comparing all pairs of positions, still passes; speed tests with long answers earn a star at about O(n log n).

Show hint

If some length-L substring repeats, so does some length-L - 1 substring, so the answer length can be searched for rather than scanned. To test one length in O(n), give each window a fingerprint you can slide in O(1) and look for two equal ones (confirming real matches).

Topic: String hashing / Rabin-Karp. Rolling polynomial hash for O(1) substring comparison.

0:00
Ctrl ' run · Ctrl ↵ submit
esc