:first-child{margin-top:0!important}.markdown-body>:last-child{margin-bottom:0!important}.markdown-body a:not([href]){color:inherit;text-decoration:none}.markdown-body .absent{color:var(--color-danger-fg)}.markdown-body .anchor{float:left;margin-left:-20px;padding-right:4px;line-height:1}.markdown-body .anchor:focus{outline:none}.markdown-body p,.markdown-body blockquote,.markdown-body ul,.markdown-body ol,.markdown-body dl,.markdown-body table,.markdown-body pre,.markdown-body details{margin-top:0;margin-bottom:16px}.markdown-body hr{height:.25em;background-color:var(--color-border-default);border:0;margin:24px 0;padding:0}.markdown-body blockquote{color:var(--color-fg-muted);border-left:.25em solid var(--color-border-default);padding:0 1em}.markdown-body blockquote>:first-child{margin-top:0}.markdown-body blockquote>:last-child{margin-bottom:0}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6{font-weight:var(--base-text-weight-semibold,600);margin-top:24px;margin-bottom:16px;line-height:1.25}.markdown-body h1 .octicon-link,.markdown-body h2 .octicon-link,.markdown-body h3 .octicon-link,.markdown-body h4 .octicon-link,.markdown-body h5 .octicon-link,.markdown-body h6 .octicon-link{color:var(--color-fg-default);vertical-align:middle;visibility:hidden}.markdown-body h1:hover .anchor,.markdown-body h2:hover .anchor,.markdown-body h3:hover .anchor,.markdown-body h4:hover .anchor,.markdown-body h5:hover .anchor,.markdown-body h6:hover .anchor{text-decoration:none}.markdown-body h1:hover .anchor .octicon-link,.markdown-body h2:hover .anchor .octicon-link,.markdown-body h3:hover .anchor .octicon-link,.markdown-body h4:hover .anchor .octicon-link,.markdown-body h5:hover .anchor .octicon-link,.markdown-body h6:hover .anchor .octicon-link{visibility:visible}.markdown-body h1 tt,.markdown-body h1 code,.markdown-body h2 tt,.markdown-body h2 code,.markdown-body h3 tt,.markdown-body h3 code,.markdown-body h4 tt,.markdown-body h4 code,.markdown-body h5 tt,.markdown-body h5 code,.markdown-body h6 tt,.markdown-body h6 code{font-size:inherit;padding:0 .2em}.markdown-body h1{border-bottom:1px solid var(--color-border-muted);padding-bottom:.3em;font-size:2em}.markdown-body h2{border-bottom:1px solid var(--color-border-muted);padding-bottom:.3em;font-size:1.5em}.markdown-body h3{font-size:1.25em}.markdown-body h4{font-size:1em}.markdown-body h5{font-size:.875em}.markdown-body h6{color:var(--color-fg-muted);font-size:.85em}.markdown-body summary h1,.markdown-body summary h2,.markdown-body summary h3,.markdown-body summary h4,.markdown-body summary h5,.markdown-body summary h6{display:inline-block}.markdown-body summary h1 .anchor,.markdown-body summary h2 .anchor,.markdown-body summary h3 .anchor,.markdown-body summary h4 .anchor,.markdown-body summary h5 .anchor,.markdown-body summary h6 .anchor{margin-left:-40px}.markdown-body summary h1,.markdown-body summary h2{border-bottom:0;padding-bottom:0}.markdown-body ul,.markdown-body ol{padding-left:2em}.markdown-body ul.no-list,.markdown-body ol.no-list{padding:0;list-style-type:none}.markdown-body ol[type=a]{list-style-type:lower-alpha}.markdown-body ol[type=A]{list-style-type:upper-alpha}.markdown-body ol[type=i]{list-style-type:lower-roman}.markdown-body ol[type=I]{list-style-type:upper-roman}.markdown-body ol[type="1"]{list-style-type:decimal}.markdown-body div>ol:not([type]){list-style-type:decimal}.markdown-body ul ul,.markdown-body ul ol,.markdown-body ol ol,.markdown-body ol ul{margin-top:0;margin-bottom:0}.markdown-body li>p{margin-top:16px}.markdown-body li+li{margin-top:.25em}.markdown-body dl{padding:0}.markdown-body dl dt{font-size:1em;font-style:italic;font-weight:var(--base-text-weight-semibold,600);margin-top:16px;padding:0}.markdown-body dl dd{margin-bottom:16px;padding:0 16px}.markdown-body table{width:100%;width:-webkit-max-content;width:-webkit-max-content;width:max-content;max-width:100%;display:block;overflow:auto}.markdown-body table th{font-weight:var(--base-text-weight-semibold,600)}.markdown-body table th,.markdown-body table td{border:1px solid var(--color-border-default);padding:6px 13px}.markdown-body table td>:last-child{margin-bottom:0}.markdown-body table tr{background-color:var(--color-canvas-default);border-top:1px solid var(--color-border-muted)}.markdown-body table tr:nth-child(2n){background-color:var(--color-canvas-subtle)}.markdown-body table img{background-color:transparent}.markdown-body img{max-width:100%;box-sizing:content-box;background-color:var(--color-canvas-default)}.markdown-body img[align=right]{padding-left:20px}.markdown-body img[align=left]{padding-right:20px}.markdown-body .emoji{max-width:none;vertical-align:text-top;background-color:transparent}.markdown-body span.frame{display:block;overflow:hidden}.markdown-body span.frame>span{float:left;width:auto;border:1px solid var(--color-border-default);margin:13px 0 0;padding:7px;display:block;overflow:hidden}.markdown-body span.frame span img{float:left;display:block}.markdown-body span.frame span span{clear:both;color:var(--color-fg-default);padding:5px 0 0;display:block}.markdown-body span.align-center{clear:both;display:block;overflow:hidden}.markdown-body span.align-center>span{text-align:center;margin:13px auto 0;display:block;overflow:hidden}.markdown-body span.align-center span img{text-align:center;margin:0 auto}.markdown-body span.align-right{clear:both;display:block;overflow:hidden}.markdown-body span.align-right>span{text-align:right;margin:13px 0 0;display:block;overflow:hidden}.markdown-body span.align-right span img{text-align:right;margin:0}.markdown-body span.float-left{float:left;margin-right:13px;display:block;overflow:hidden}.markdown-body span.float-left span{margin:13px 0 0}.markdown-body span.float-right{float:right;margin-left:13px;display:block;overflow:hidden}.markdown-body span.float-right>span{text-align:right;margin:13px auto 0;display:block;overflow:hidden}.markdown-body code,.markdown-body tt{white-space:break-spaces;background-color:var(--color-neutral-muted);border-radius:6px;margin:0;padding:.2em .4em;font-size:85%}.markdown-body code br,.markdown-body tt br{display:none}.markdown-body del code{-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}.markdown-body samp{font-size:85%}.markdown-body pre{word-wrap:normal}.markdown-body pre code{font-size:100%}.markdown-body pre>code{word-break:normal;white-space:pre;background:0 0;border:0;margin:0;padding:0}.markdown-body .highlight{margin-bottom:16px}.markdown-body .highlight pre{word-break:normal;margin-bottom:0}.markdown-body .highlight pre,.markdown-body pre{background-color:var(--color-canvas-subtle);border-radius:6px;padding:16px;font-size:85%;line-height:1.45;overflow:auto}.markdown-body pre code,.markdown-body pre tt{max-width:auto;line-height:inherit;word-wrap:normal;background-color:transparent;border:0;margin:0;padding:0;display:inline;overflow:visible}.markdown-body .csv-data td,.markdown-body .csv-data th{text-align:left;white-space:nowrap;padding:5px;font-size:12px;line-height:1;overflow:hidden}.markdown-body .csv-data .blob-num{text-align:right;background:var(--color-canvas-default);border:0;padding:10px 8px 9px}.markdown-body .csv-data tr{border-top:0}.markdown-body .csv-data th{font-weight:var(--base-text-weight-semibold,600);background:var(--color-canvas-subtle);border-top:0}.markdown-body [data-footnote-ref]:before{content:"["}.markdown-body [data-footnote-ref]:after{content:"]"}.markdown-body .footnotes{color:var(--color-fg-muted);border-top:1px solid var(--color-border-default);font-size:12px}.markdown-body .footnotes ol{padding-left:16px}.markdown-body .footnotes ol ul{margin-top:16px;padding-left:16px;display:inline-block}.markdown-body .footnotes li{position:relative}.markdown-body .footnotes li:target:before{pointer-events:none;content:"";border:2px solid var(--color-accent-emphasis);border-radius:6px;position:absolute;top:-8px;bottom:-8px;left:-24px;right:-8px}.markdown-body .footnotes li:target{color:var(--color-fg-default)}.markdown-body .footnotes .data-footnote-backref g-emoji{font-family:monospace}.markdown-body{background-color:var(--color-canvas-default);color:var(--color-fg-default)}.markdown-body a{color:var(--color-accent-fg);text-decoration:none}.markdown-body a:hover{text-decoration:underline}.markdown-body img[align=center]{margin:0 auto}.markdown-body iframe{background-color:#fff;border:0;margin-bottom:16px}.markdown-body svg.octicon{fill:currentColor}.markdown-body .anchor>.octicon{display:inline}.markdown-body figcaption{text-align:center;padding-top:2px}.markdown-body .highlight .token.keyword,.gfm-highlight .token.keyword{color:var(--color-prettylights-syntax-keyword)}.markdown-body .highlight .token.tag .token.class-name,.markdown-body .highlight .token.tag .token.script .token.punctuation,.gfm-highlight .token.tag .token.class-name,.gfm-highlight .token.tag .token.script .token.punctuation{color:var(--color-prettylights-syntax-storage-modifier-import)}.markdown-body .highlight .token.operator,.markdown-body .highlight .token.number,.markdown-body .highlight .token.boolean,.markdown-body .highlight .token.tag .token.punctuation,.markdown-body .highlight .token.tag .token.script .token.script-punctuation,.markdown-body .highlight .token.tag .token.attr-name,.gfm-highlight .token.operator,.gfm-highlight .token.number,.gfm-highlight .token.boolean,.gfm-highlight .token.tag .token.punctuation,.gfm-highlight .token.tag .token.script .token.script-punctuation,.gfm-highlight .token.tag .token.attr-name{color:var(--color-prettylights-syntax-constant)}.markdown-body .highlight .token.function,.gfm-highlight .token.function{color:var(--color-prettylights-syntax-entity)}.markdown-body .highlight .token.string,.gfm-highlight .token.string{color:var(--color-prettylights-syntax-string)}.markdown-body .highlight .token.comment,.gfm-highlight .token.comment{color:var(--color-prettylights-syntax-comment)}.markdown-body .highlight .token.class-name,.gfm-highlight .token.class-name{color:var(--color-prettylights-syntax-variable)}.markdown-body .highlight .token.regex,.gfm-highlight .token.regex{color:var(--color-prettylights-syntax-string)}.markdown-body .highlight .token.regex .regex-delimiter,.gfm-highlight .token.regex .regex-delimiter{color:var(--color-prettylights-syntax-constant)}.markdown-body .highlight .token.tag .token.tag,.markdown-body .highlight .token.property,.gfm-highlight .token.tag .token.tag,.gfm-highlight .token.property{color:var(--color-prettylights-syntax-entity-tag)}.markdown-body .highlight .token.deleted,.gfm-highlight .token.deleted{color:var(--color-prettylights-syntax-markup-deleted-text);background-color:var(--color-prettylights-syntax-markup-deleted-bg)}.markdown-body .highlight .token.inserted,.gfm-highlight .token.inserted{color:var(--color-prettylights-syntax-markup-inserted-text);background-color:var(--color-prettylights-syntax-markup-inserted-bg)}

Longest prefix which is also suffix (original) (raw)

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.

Try It Yourselfredirect icon

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.

C++ `

#include #include 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 #include #include 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:

#include #include #include 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));

`