KatInterview

Max Overlap of String Suffix and Prefix

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringsstringskmpprefix-function

Last 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 first matching a prefix of second.
  • 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$
  • first and second consist 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.