Longest Proper Prefix That Is Also a Suffix

Quick Overview

Longest Proper Prefix That Is Also a Suffix. Return the longest nonempty prefix of s that is also a suffix, excluding s itself.

Longest Proper Prefix That Is Also a Suffix

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

### Problem Return the longest nonempty prefix of s that is also a suffix, excluding s itself. The prefix and suffix occurrences may overlap. Return the empty string when no such nonempty proper prefix exists. ```cpp class Solution { public: string longestPrefix(string s); }; ``` ### Examples **Example 1:** ```text Input: s = "aaaa" Output: "aaa" Explanation: The length3 prefix and suffix overlap and are equal; length4 is forbidden because it is the whole string. ``` **Example 2:** ```text Input: s = "abcd" Output: "" Explanation: No nonempty proper prefix matches a suffix. ``` ### Constraints - s has length 1 to 100000. - Every character is a lowercase English letter. ### Contract considerations The result is uniquely determined by its maximal length. ```hint Read the boundary condition Check overlapping prefix and suffix occurrences, a one-letter string, and the exclusion of the entire string. ``` ### Boundary reminders The result is uniquely determined by its maximal length.

Overview: Longest Proper Prefix That Is Also a Suffix. Return the longest nonempty prefix of s that is also a suffix, excluding s itself.

Google logo
Google
Source window: 0–3 months · as of Oct 21, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return the longest nonempty prefix of s that is also a suffix, excluding s itself. The prefix and suffix occurrences may overlap. Return the empty string when no such nonempty proper prefix exists.

class Solution {
public:
    string longestPrefix(string s);
};

Examples

Example 1:

Input: s = "aaaa"
Output: "aaa"
Explanation: The length3 prefix and suffix overlap and are equal; length4 is forbidden because it is the whole string.

Example 2:

Input: s = "abcd"
Output: ""
Explanation: No nonempty proper prefix matches a suffix.

Constraints

  • s has length 1 to 100000.
  • Every character is a lowercase English letter.

Contract considerations

The result is uniquely determined by its maximal length.

Boundary reminders

The result is uniquely determined by its maximal length.