Longest prefix which is also suffix
Last Updated :
25 Jul, 2025
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.
[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.
C++
#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;
}
C
#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;
}
Java
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));
}
}
Python
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))
C#
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));
}
}
JavaScript
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));
[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.
C++
#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;
}
C
#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;
}
Java
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));
}
}
Python
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))
C#
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));
}
}
JavaScript
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));
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.
C++
#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;
}
Java
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));
}
}
Python
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))
C#
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));
}
}
JavaScript
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));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data Structure GuideIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem