Max Overlap of String Suffix and Prefix
StringsAuto-graded · 23 test casesLast updated
Find the maximum length of a suffix of one string that matches a prefix of another.
Given two strings first and second, determine the maximum length $k$ such that the ending segment of first (a suffix of length $k$) matches the starting segment of second (a prefix of length $k$).
Return the integer $k$. If no non-empty suffix of first matches a prefix of second, return 0.
Rules
- The overlap is strictly directional: it must be a suffix of
firstmatching a prefix ofsecond. - The maximum possible overlap length is bounded by $\min(\text{len}(first), \text{len}(second))$.
- Character comparisons are case-sensitive and exact.
Constraints
- $1 \le \text{len}(first) \le 10^4$
- $1 \le \text{len}(second) \le 10^4$
firstandsecondconsist only of lowercase English characters (a-z).
Examples
Example 1
Input: max_overlap('abcde', 'cdefg')
Output: 3
Example 2
Input: max_overlap('hello', 'lohel')
Output: 2
Example 3
Input: max_overlap('abc', 'xyz')
Output: 0
Hints
Hint 1
The overlap length cannot exceed min(len(first), len(second)). You can trim first to its last m characters and second to its first m characters.
Hint 2
This problem asks for the longest string that is both a suffix of one text and a prefix of another. Consider using the KMP prefix function (pi table).
Hint 3
Concatenate second_prefix + '#' + first_suffix and compute the KMP table. The value at the last position gives the longest valid overlap.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The goal is to find the maximum integer $k \ge 0$ such that the last $k$ characters of first equal the first $k$ characters of second.
-
Bounding the Search Space: The overlap length $k$ cannot exceed $m = \min(\text{len}(first), \text{len}(second))$. Therefore, we only care about the prefix of
secondof length $m$ and the suffix offirstof length $m$. -
Knuth-Morris-Pratt (KMP) Prefix Function: The KMP failure function (or $\pi$-array) computes the length of the longest proper prefix of a string that is also a suffix of that string.
If we construct a single string: $$\text{combined} = \text{second}[:m] + \text{'#'} + \text{first}[\text{len}(first) - m:]$$
The sentinel character
'#'guarantees that no match can extend across the boundary. The length of the longest proper prefix ofcombinedthat is also a suffix ofcombinedwill be represented by $\pi[-1]$. Because'#'appears only once in the middle, any matching prefix-suffix pair of length $\le m$ corresponds to a prefix ofsecondmatching a suffix offirst.
Algorithm Steps
- Calculate $m = \min(\text{len}(first), \text{len}(second))$.
- Construct
combined = second[:m] + "#" + first[len(first) - m:]. - Build the $\pi$ array for
combined:- For each index $i$ from $1$ to $\text{len}(combined) - 1$, maintain the longest border length $j = \pi[i-1]$.
- Fall back via $j = \pi[j-1]$ while characters do not match.
- If characters match, increment $j$ and set $\pi[i] = j$.
- Return $\pi[-1]$.
Complexity Analysis
- Time Complexity: $\mathcal{O}(m)$ where $m = \min(\text{len}(first), \text{len}(second))$. String slicing takes $\mathcal{O}(m)$, and building the KMP $\pi$ array takes amortized linear time $\mathcal{O}(m)$ since the match pointer $j$ increments at most once per iteration.
- Space Complexity: $\mathcal{O}(m)$ to store the concatenated string and the $\pi$ array.
Python Reference Solution
def max_overlap(first: str, second: str) -> int:
limit = min(len(first), len(second))
combined = second[:limit] + "#" + first[len(first) - limit:]
pi = [0] * len(combined)
for i in range(1, len(combined)):
j = pi[i - 1]
while j > 0 and combined[i] != combined[j]:
j = pi[j - 1]
if combined[i] == combined[j]:
j += 1
pi[i] = j
return pi[-1]