Longest Substring That Occurs at Least Twice, Overlaps Allowed
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: A string algorithms problem: given a lowercase string of up to 30,000 characters, return the longest substring that occurs at least twice, where occurrences may overlap and ties go to the lexicographically smallest substring. It tests efficient repeated-substring search on long inputs, where a quadratic scan is too slow.
Constraints
- 1 <= len(s) <= 3 * 10^4
- s consists only of lowercase English letters 'a' to 'z'.
Examples
Input: ('a',)
Expected Output: ''
Explanation: Minimum length 1: a single character cannot occur twice, so the answer is empty.
Input: ('aa',)
Expected Output: 'a'
Explanation: Smallest input with a repeat: 'a' occurs at positions 0 and 1, while 'aa' occurs once.
Hints
- Occurrences may overlap: in a string made of one repeated letter, the longest repeated substring is only one character shorter than the whole string.
- If a substring of length L occurs at two different positions, then every shorter piece cut from the same two starting positions also occurs twice, so the achievable repeat lengths have no gaps.
- With up to 3 * 10^4 characters, comparing every pair of starting positions character by character is far too slow; aim for close to n log n work, and apply the smallest-string tie-break only among candidates of the maximum length.