Longest proper prefix that is also a suffix
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft. It tests strings, kmp and prefix function.
Given a string s, return the length of the longest string that is both a proper prefix and a proper suffix of s.
- A prefix is a run of characters at the start of
s; a suffix is a run at the end. -
Proper means the whole string does not count. So the answer is always less than
len(s). - The prefix and the suffix may overlap inside
s. - If no such non-empty string exists, return
0.
Implement:
def longest_prefix_suffix(s: str) -> int: ...
Constraints
0 <= len(s) <= 10^5-
scontains lowercase English letters. - Aim for better than O(n^2) time.
Examples
Example 1
Input: s = "abcabcab"
Output: 5
"abcab" is the first five characters and also the last five. The two copies overlap in the middle.
Example 2
Input: s = "pqrs"
Output: 0
No non-empty proper prefix matches the suffix of the same length.
Clarifying questions
- Should the empty string and a one-character string both return
0? - Is the comparison case-sensitive?
- Are overlapping matches allowed? (Yes, per the statement.)
- Is a hash-based answer acceptable, or must it be exact?
What a strong answer covers
- Uses the KMP prefix function. Its last value is the answer. That is O(n) time and O(n) memory.
- Explains how the prefix function falls back along shorter borders when a character does not match, and why the total work stays linear.
- Or uses the Z-function, or rolling hashes compared from longest to shortest, and names the collision risk of hashing.
- Tests
"aaaa"(answer 3),"abcabcab","pqrs","aba"and the empty string.
Follow-ups
- List every border, not only the longest.
- The prefix and the suffix must not overlap.
- Find the shortest period of the string.
- Use this to find every occurrence of a pattern in a text.
Where it's asked
What it tests
strings · kmp · prefix function
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
