πŸš€5. Longest Prefix Suffix 🧠

The problem can be found at the following link: Problem Link

πŸ’‘ Problem Description:

Given a string s, find the length of the longest prefix which is also a suffix. Note: The prefix and suffix can be overlapping, but they should not be equal to the entire string.

πŸ” Example Walkthrough:

Input:

s = "abab"

Output:

2

Explanation: "ab" is the longest prefix and suffix.

Input:

s = "aabcdaabc"

Output:

4

Explanation: The string "aabc" is the longest prefix and suffix.

Input:

s = "aaaa"

Output:

Explanation: "aaa" is the longest prefix and suffix.

Constraints:

  • $1 \leq s.size() \leq 10^6$

  • The string s contains only lowercase English alphabets.

🎯 My Approach:

  1. LPS Array (Longest Prefix Suffix): We will use an auxiliary array lps[] to store the length of the longest proper prefix which is also a suffix for each substring ending at index i. The idea is based on the Knuth-Morris-Pratt (KMP) string matching algorithm.

  2. Traverse the String:

    • Start by initializing two variables:

      • len = 0 which tracks the length of the current longest prefix suffix.

      • i = 1 which is the current position in the string.

    • For each character at position i, if it matches the character at position len, it extends the current prefix-suffix, so we increment len and move to the next character.

    • If there’s a mismatch, instead of simply moving forward, we use the lps[len - 1] value to jump to a smaller possible prefix-suffix length, thus avoiding unnecessary comparisons.

  3. Final Answer: The value at lps[n-1] (where n is the length of the string) gives the length of the longest proper prefix which is also a suffix.

πŸ•’ Time and Auxiliary Space Complexity:

  • Time Complexity: The algorithm runs in O(n) time, where n is the length of the string. This is because we traverse the string once while constructing the lps array.

  • Space Complexity: The space complexity is O(n), as we need an auxiliary array lps[] of size n to store the prefix-suffix lengths.

πŸ“ Solution Code

Code (Cpp)

Code (Java)

Code (Python)

🎯 Contribution and Support:

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Last updated