Given a string s, find the length of the longest proper prefix which is also a suffix. A proper prefix is a prefix that doesn’t include whole string. For example, prefixes of "abc" are "", "a", "ab" and "abc" but proper prefixes are "", "a" and "ab" only.
Examples:
Input: s = "aabcdaabc"
Output: 4
Explanation: The string "aabc" is the longest proper prefix which is also the suffix.Input: s = "ababab"
Output: 4
Explanation: The string "abab" is the longest proper prefix which is also the suffix.Input: s = "aaaa"
Output: 3
Explanation: The string "aaa" is the longest proper prefix which is also the suffix.
Table of Content
[Naive approach] Naive Prefix-Suffix Match - O(n2) Time and O(1) Space
The idea is to compare each proper prefix of the string with its corresponding suffix. A proper prefix has a length ranging from 0 to n - 1. For each possible length, we check if the prefix of that size matches the suffix of the same size. If a match is found, we update the result with the maximum matching length. This brute-force method ensures we find the longest prefix which is also a suffix.
#include <iostream>
#include <string>
using namespace std;
int getLPSLength(string s) {
int res = 0;
int n = s.length();
// iterating over all possible lengths
for (int len = 1; len < n; len++) {
// Starting index of suffix
int j = s.length() - len;
bool flag = true;
// comparing proper prefix with suffix of length 'len'
for (int k = 0; k < len; k++) {
if (s[k] != s[j + k]) {
flag = false;
break;
}
}
// if they match, update the result
if (flag)
res = len;
}
return res;
}
int main() {
string s = "ababab";
cout << getLPSLength(s);
return 0;
}
#include <stdio.h>
#include <string.h>
int getLPSLength(char s[]) {
int res = 0;
int n = strlen(s);
// iterating over all possible lengths
for (int len = 1; len < n; len++) {
// starting index of suffix
int j = n - len;
int flag = 1;
// comparing proper prefix with suffix
// of length 'len'
for (int k = 0; k < len; k++) {
if (s[k] != s[j + k]) {
flag = 0;
break;
}
}
// if they match, update the result
if (flag)
res = len;
}
return res;
}
int main() {
char s[] = "ababab";
printf("%d", getLPSLength(s));
return 0;
}
class GfG {
static int getLPSLength(String s) {
int res = 0;
int n = s.length();
// iterating over all possible lengths
for (int len = 1; len < n; len++) {
// starting index of suffix
int j = s.length() - len;
boolean flag = true;
// comparing proper prefix with suffix of length 'len'
for (int k = 0; k < len; k++) {
if (s.charAt(k) != s.charAt(j + k)) {
flag = false;
break;
}
}
// if they match, update the result
if (flag)
res = len;
}
return res;
}
public static void main(String[] args) {
String s = "ababab";
System.out.println(getLPSLength(s));
}
}
def getLPSLength(s):
res = 0
n = len(s)
# iterating over all possible lengths
for length in range(1, n):
# starting index of suffix
j = n - length
flag = True
# comparing proper prefix with suffix of length 'len'
for k in range(length):
if s[k] != s[j + k]:
flag = False
break
# if they match, update the result
if flag:
res = length
return res
if __name__ == "__main__":
s = "ababab"
print(getLPSLength(s))
using System;
class GfG {
static int getLPSLength(string s) {
int res = 0;
int n = s.Length;
// iterating over all possible lengths
for (int len = 1; len < n; len++) {
// starting index of suffix
int j = s.Length - len;
bool flag = true;
// Comparing proper prefix with suffix
// of length 'len'
for (int k = 0; k < len; k++) {
if (s[k] != s[j + k]) {
flag = false;
break;
}
}
// if they match, update the result
if (flag)
res = len;
}
return res;
}
static void Main() {
string s = "ababab";
Console.WriteLine(getLPSLength(s));
}
}
function getLPSLength(s) {
let res = 0;
let n = s.length;
// iterating over all possible lengths
for (let len = 1; len < n; len++) {
// starting index of suffix
let j = n - len;
let flag = true;
// comparing proper prefix with suffix
// of length 'len'
for (let k = 0; k < len; k++) {
if (s[k] !== s[j + k]) {
flag = false;
break;
}
}
// if they match, update the result
if (flag)
res = len;
}
return res;
}
// Driver Code
let s = "ababab";
console.log(getLPSLength(s));
Output
4
[Expected approach] Using LPS of KMP Algorithm
The idea is to use the preprocessing step of the KMP (Knuth-Morris-Pratt) algorithm. In this step, we construct an LPS (Longest Prefix Suffix) array, where each index i stores the length of the longest proper prefix of the substring str[0...i] that is also a suffix of the same substring. The value at the last index of the LPS array represents the length of the longest proper prefix which is also a suffix for the entire string.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int getLPSLength(string& s) {
int n = s.size();
// initialize LPS array with 0s
vector<int> lps(n, 0);
// length of the previous longest
// prefix-suffix
int len = 0;
int i = 1;
while (i < n) {
if (s[i] == s[len]) {
lps[i] = ++len;
i++;
}
else{
if (len != 0) {
// Fall back in the LPS array
len = lps[len - 1];
}
else{
lps[i] = 0;
i++;
}
}
}
// lps[n - 1] holds the result for
// the entire string
return lps[n - 1];
}
int main() {
string s = "ababab";
cout << getLPSLength(s) << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
int getLPSLength(char s[]) {
int n = strlen(s);
int lps[n];
// length of the previous longest
// prefix-suffix
int len = 0;
// lps[0] is always 0
lps[0] = 0;
int i = 1;
while (i < n) {
if (s[i] == s[len]) {
len++;
lps[i] = len;
i++;
}
else {
if (len != 0) {
// fall back in the LPS array
len = lps[len - 1];
}
else {
lps[i] = 0;
i++;
}
}
}
// lps[n - 1] holds the result for
// the entire string
return lps[n - 1];
}
int main() {
char s[] = "ababab";
printf("%d", getLPSLength(s));
return 0;
}
import java.util.*;
class GfG {
public static int getLPSLength(String s) {
int n = s.length();
// initialize LPS array with 0s
int[] lps = new int[n];
// length of the previous longest
// prefix-suffix
int len = 0;
int i = 1;
while (i < n) {
if (s.charAt(i) == s.charAt(len)) {
lps[i] = ++len;
i++;
}
else{
if (len != 0) {
// fall back in the LPS array
len = lps[len - 1];
}
else{
lps[i] = 0;
i++;
}
}
}
// lps[n - 1] holds the result for
// the entire string
return lps[n - 1];
}
public static void main(String[] args) {
String s = "ababab";
System.out.println(getLPSLength(s));
}
}
def getLPSLength(s):
n = len(s)
# initialize LPS array with 0s
lps = [0] * n
# length of the previous longest
# prefix-suffix
len_ = 0
i = 1
while i < n:
if s[i] == s[len_]:
len_ += 1
lps[i] = len_
i += 1
else:
if len_ != 0:
# fall back in the LPS array
len_ = lps[len_ - 1]
else:
lps[i] = 0
i += 1
# lps[n - 1] holds the result for
# the entire string
return lps[n - 1]
if __name__ == "__main__":
s = "ababab"
print(getLPSLength(s))
using System;
class GfG {
public static int getLPSLength(string s) {
int n = s.Length;
// initialize LPS array with 0s
int[] lps = new int[n];
// length of the previous longest
// prefix-suffix
int len = 0;
int i = 1;
while (i < n) {
if (s[i] == s[len]) {
lps[i] = ++len;
i++;
}
else{
if (len != 0) {
// fall back in the LPS array
len = lps[len - 1];
}
else{
lps[i] = 0;
i++;
}
}
}
// lps[n - 1] holds the result for
// the entire string
return lps[n - 1];
}
public static void Main() {
string s = "ababab";
Console.WriteLine(getLPSLength(s));
}
}
function getLPSLength(s) {
let n = s.length;
// initialize LPS array with 0s
let lps = new Array(n).fill(0);
// length of the previous longest
// prefix-suffix
let len = 0;
let i = 1;
while (i < n) {
if (s[i] === s[len]) {
lps[i] = ++len;
i++;
} else {
if (len !== 0) {
// fall back in the LPS array
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
// lps[n - 1] holds the result for
// the entire string
return lps[n - 1];
}
// Driver Code
let s = "ababab";
console.log(getLPSLength(s));
Output
4
Time Complexity: O(n) we iterate through the string once using the i pointer, and in the worst case, each character is processed at most twice (once when matched, once when falling back via len = lps[len - 1]).
Auxiliary Space: O(n)
[Efficient Approach] Double Hash Prefix-Suffix Check - O(n) Time and O(1) Space
The idea is to use double rolling hash to compute and compare the hash values of the prefix and suffix of every possible length from 1 to n-1.
We update prefix and suffix hashes in each iteration and check if they match. If both hashes match, we update the result with the current length. Using two moduli reduces the risk of hash collisions and ensures correctness.
Step by Step Implementation:
- Initialize constants - two bases (base1, base2) and two mod values (mod1, mod2) for double hashing.
- Initialize:
-> Prefix powers p1, p2 as 1.
-> Hash arrays: hash1 and hash2 (both of size 2) to store prefix and suffix hashes.
-> ans to store the final result. - Loop through the string from index 0 to n-2:
-> Update hash1[0] and hash1[1] by adding current character's weighted value to the prefix hash.
-> Update hash2[0] and hash2[1] by appending character from the end to the suffix hash. - If both pairs match, update ans = i + 1.
- Multiply p1 with base1, and p2 with base2 under mod.
- Return ans as the length of the longest prefix which is also a suffix.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int getLPSLength(string &s) {
int base1 = 31, base2 = 37;
int mod1 = 1e9 + 7, mod2 = 1e9 + 9;
int p1 = 1, p2 = 1;
int n = s.size();
// hash1 for prefix, hash2 for suffix
vector<int> hash1(2, 0), hash2(2, 0);
int ans = 0;
for (int i = 0; i < n - 1; i++) {
// Update prefix hashes
hash1[0] = (hash1[0] + 1LL *
(s[i] - 'a' + 1) * p1 % mod1) % mod1;
hash1[1] = (hash1[1] + 1LL *
(s[i] - 'a' + 1) * p2 % mod2) % mod2;
// Update suffix hashes
hash2[0] = (1LL * hash2[0] * base1 % mod1 +
(s[n - i - 1] - 'a' + 1)) % mod1;
hash2[1] = (1LL * hash2[1] * base2 % mod2 +
(s[n - i - 1] - 'a' + 1)) % mod2;
// Check if both hash pairs match
if (hash1 == hash2) {
ans = i + 1;
}
// Update powers
p1 = 1LL * p1 * base1 % mod1;
p2 = 1LL * p2 * base2 % mod2;
}
return ans;
}
int main() {
string s = "ababab";
cout << getLPSLength(s) << endl;
return 0;
}
class GfG {
public static int getLPSLength(String s) {
int base1 = 31, base2 = 37;
int mod1 = 1000000007, mod2 = 1000000009;
int p1 = 1, p2 = 1;
int n = s.length();
// hash1 for prefix, hash2 for suffix
int[] hash1 = new int[]{0, 0};
int[] hash2 = new int[]{0, 0};
int ans = 0;
for (int i = 0; i < n - 1; i++) {
// Update prefix hashes
hash1[0] = (int)((hash1[0] +
1L * (s.charAt(i) - 'a' + 1) * p1 % mod1) % mod1);
hash1[1] = (int)((hash1[1] +
1L * (s.charAt(i) - 'a' + 1) * p2 % mod2) % mod2);
// Update suffix hashes
hash2[0] = (int)((1L * hash2[0] * base1 % mod1 +
(s.charAt(n - i - 1) - 'a' + 1)) % mod1);
hash2[1] = (int)((1L * hash2[1] * base2 % mod2 +
(s.charAt(n - i - 1) - 'a' + 1)) % mod2);
// Check if both hash pairs match
if (hash1[0] == hash2[0] && hash1[1] == hash2[1]) {
ans = i + 1;
}
// Update powers
p1 = (int)(1L * p1 * base1 % mod1);
p2 = (int)(1L * p2 * base2 % mod2);
}
return ans;
}
public static void main(String[] args) {
String s = "ababab";
System.out.println(getLPSLength(s));
}
}
def getLPSLength(s):
base1, base2 = 31, 37
mod1, mod2 = int(1e9 + 7), int(1e9 + 9)
p1 = p2 = 1
n = len(s)
# hash1 for prefix, hash2 for suffix
hash1 = [0, 0]
hash2 = [0, 0]
ans = 0
for i in range(n - 1):
# Update prefix hashes
hash1[0] = (hash1[0] + (ord(s[i]) - \
ord('a') + 1) * p1) % mod1
hash1[1] = (hash1[1] + (ord(s[i]) - \
ord('a') + 1) * p2) % mod2
# Update suffix hashes
hash2[0] = (hash2[0] * base1 + \
(ord(s[n - i - 1]) - ord('a') + 1)) % mod1
hash2[1] = (hash2[1] * base2 + \
(ord(s[n - i - 1]) - ord('a') + 1)) % mod2
# Check if both hash pairs match
if hash1 == hash2:
ans = i + 1
# Update powers
p1 = (p1 * base1) % mod1
p2 = (p2 * base2) % mod2
return ans
if __name__ == "__main__":
s = "ababab"
print(getLPSLength(s))
using System;
class GfG {
public static int getLPSLength(string s) {
int base1 = 31, base2 = 37;
int mod1 = 1000000007, mod2 = 1000000009;
int p1 = 1, p2 = 1;
int n = s.Length;
// hash1 for prefix, hash2 for suffix
int[] hash1 = new int[] { 0, 0 };
int[] hash2 = new int[] { 0, 0 };
int ans = 0;
for (int i = 0; i < n - 1; i++) {
// Update prefix hashes
hash1[0] = (int)((hash1[0] +
1L * (s[i] - 'a' + 1) * p1 % mod1) % mod1);
hash1[1] = (int)((hash1[1] +
1L * (s[i] - 'a' + 1) * p2 % mod2) % mod2);
// Update suffix hashes
hash2[0] = (int)((1L * hash2[0] * base1 % mod1 +
(s[n - i - 1] - 'a' + 1)) % mod1);
hash2[1] = (int)((1L * hash2[1] * base2 % mod2 +
(s[n - i - 1] - 'a' + 1)) % mod2);
// Check if both hash pairs match
if (hash1[0] == hash2[0] && hash1[1] == hash2[1]) {
ans = i + 1;
}
// Update powers
p1 = (int)(1L * p1 * base1 % mod1);
p2 = (int)(1L * p2 * base2 % mod2);
}
return ans;
}
public static void Main() {
string s = "ababab";
Console.WriteLine(getLPSLength(s));
}
}
function getLPSLength(s) {
let base1 = 31, base2 = 37;
let mod1 = 1e9 + 7, mod2 = 1e9 + 9;
let p1 = 1, p2 = 1;
let n = s.length;
// hash1 for prefix, hash2 for suffix
let hash1 = [0, 0], hash2 = [0, 0];
let ans = 0;
for (let i = 0; i < n - 1; i++) {
// Update prefix hashes
hash1[0] = (hash1[0] +
((s.charCodeAt(i) - 96) * p1) % mod1) % mod1;
hash1[1] = (hash1[1] +
((s.charCodeAt(i) - 96) * p2) % mod2) % mod2;
// Update suffix hashes
hash2[0] = (hash2[0] * base1 % mod1 +
(s.charCodeAt(n - i - 1) - 96)) % mod1;
hash2[1] = (hash2[1] * base2 % mod2 +
(s.charCodeAt(n - i - 1) - 96)) % mod2;
// Check if both hash pairs match
if (hash1[0] === hash2[0] && hash1[1] === hash2[1]) {
ans = i + 1;
}
// Update powers
p1 = p1 * base1 % mod1;
p2 = p2 * base2 % mod2;
}
return ans;
}
// Driver Code
let s = "ababab";
console.log(getLPSLength(s));