Longest Overlap Between the End of One String and the Start of Another
CrestaSoftware Engineer · Online AssessmentLast updated
Given two strings, return the length of the longest suffix of the first string that is also a prefix of the second. The problem tests precise string indexing, the direction of the overlap, and boundary cases such as no overlap at all or an overlap covering the whole shorter string.
Given two strings a and b, find the longest stretch at the end of a that is also the beginning of b. Return its length: the largest k such that the last k characters of a are the same as the first k characters of b.
Function Signature
def max_overlap(a: str, b: str) -> int:
Rules
kranges from 0 tomin(len(a), len(b)), and it may equal the full length of the shorter string.- The direction matters: the overlap is always the end of
aagainst the start ofb, never the end ofbagainst the start ofa. - Characters are compared exactly, one by one.
- If no
k >= 1works, return 0.
Constraints
1 <= len(a) <= 10^4and1 <= len(b) <= 10^4aandbconsist of lowercase English letters
Examples
Example 1
Input: a = "abcde", b = "cdefg"
Output: 3
The last three characters of a, cde, are the first three characters of b. No longer stretch works: bcde is not cdef, and abcde is not cdefg.
Example 2
Input: a = "hello", b = "lohel"
Output: 2
The last two characters of a, lo, are the first two of b. With the arguments swapped the answer would be 3 (hel), which shows that the direction matters.
Example 3
Input: a = "abc", b = "xyz"
Output: 0
No suffix of a is a prefix of b.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.