← Questions

Longest proper prefix that is also a suffix

0
MicrosoftCoding

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
  • s contains 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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding