08. Longest Prefix Suffix
β GFG solution to the Longest Prefix Suffix problem: find the length of longest proper prefix which is also a suffix using KMP's LPS array construction technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given a string s of lowercase English alphabets, find the length of the longest proper prefix which is also a suffix.
Note: Prefix and suffix can be overlapping but they should not be equal to the entire string.
A proper prefix is a prefix that is not equal to the string itself. Similarly, a proper suffix is a suffix that is not equal to the string itself.
π Examples
Example 1
Input: s = "abab"
Output: 2
Explanation: The string "ab" is the longest prefix and suffix.Example 2
Input: s = "aabcdaabc"
Output: 4
Explanation: The string "aabc" is the longest prefix and suffix.Example 3
π Constraints
$1 \le s.size() \le 10^6$
s contains only lowercase English alphabets.
β
My Approach
The optimal approach uses the KMP (Knuth-Morris-Pratt) Algorithm's LPS Array Construction technique:
KMP LPS Array Construction
Initialize Variables:
Create an LPS array of size
nwherelps[i]stores the length of longest proper prefix which is also suffix for substrings[0...i].Use two pointers:
i(current position) andj(length of current matching prefix).
Build LPS Array:
Start with
i = 1andj = 0(sincelps[0]is always 0).If characters match (
s[i] == s[j]), increment both pointers and setlps[i] = j.If characters don't match and
j > 0, movejtolps[j-1](fallback position).If characters don't match and
j == 0, setlps[i] = 0and incrementi.
Extract Result:
The answer is
lps[n-1]which gives the length of longest proper prefix-suffix for the entire string.
Key Insight:
The LPS array construction efficiently handles all overlapping cases by using previously computed values.
Time complexity remains linear due to the amortized analysis of pointer movements.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the length of the string. Although there are nested loops, the inner while loop's total iterations across all outer loop iterations is bounded by n, making it linear overall.
Expected Auxiliary Space Complexity: O(n), as we use an additional LPS array of size n to store the longest proper prefix-suffix lengths.
π§βπ» Code (C++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Rolling Hash Approach
π‘ Algorithm Steps:
Use double hashing with two different bases to avoid collisions.
Build prefix hash from left and suffix hash from right simultaneously.
Compare hash values at each position to find matching prefix-suffix pairs.
Track the maximum length where prefix hash equals suffix hash.
π Complexity Analysis:
Time: β±οΈ O(n) - Single pass with hash computations
Auxiliary Space: πΎ O(1) - Only constant variables used
β
Why This Approach?
Constant space complexity
Good for very long strings
Hash-based pattern matching technique
π 3οΈβ£ Brute Force with Optimization
π‘ Algorithm Steps:
Check each possible prefix-suffix pair starting from the longest.
Use early termination when mismatch is found.
Compare characters from both ends moving inward.
Return the first (longest) matching prefix-suffix length.
π Complexity Analysis:
Time: β±οΈ O(nΒ²) - Nested loops for checking all possibilities
Auxiliary Space: πΎ O(1) - No additional data structures
β
Why This Approach?
Simple and intuitive logic
Space efficient implementation
Good for small strings or educational purposes
π 4οΈβ£ Z-Algorithm Based Approach
π‘ Algorithm Steps:
Apply Z-algorithm to find all prefix matches throughout the string.
Check positions where Z[i] + i equals string length (suffix matches prefix).
Among all such positions, find the maximum Z[i] value.
This represents the longest proper prefix that is also a suffix.
π Complexity Analysis:
Time: β±οΈ O(n) - Linear time Z-algorithm computation
Auxiliary Space: πΎ O(n) - Z-array storage
β
Why This Approach?
Alternative linear time solution
Useful for multiple string pattern problems
Educational value for understanding Z-algorithm
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π·οΈ KMP LPS Array
π’ O(n)
π‘ O(n)
π Standard optimal solution
πΎ Extra array space
π Rolling Hash
π’ O(n)
π’ O(1)
πΎ Constant space usage
π² Hash collision possibility
π Brute Force
π‘ O(nΒ²)
π’ O(1)
π Simple to understand
π Quadratic time complexity
π Z-Algorithm
π’ O(n)
π‘ O(n)
β Alternative linear approach
π§ More complex to understand
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Standard Implementation
π₯ KMP LPS Array
β β β β β
πΎ Memory Constraints
π₯ Rolling Hash
β β β β β
π Learning/Teaching
π₯ Brute Force
β β β ββ
π― Advanced Algorithms
π Z-Algorithm
β β β β β
β 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