Open In App

Palindrome Substring Queries

Last Updated : 29 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s and a 2D list of queries[][], where each queries[i] consists of two integers [left, right]. Each query refers to the substring s[left : right], where both left and right are inclusive (0-based indexing).
For each query, find whether the substring s[left : right] forms a palindrome.

Examples : 

Input: s = "abaaabaaaba", queries[][] = [[0, 10], [5, 8], [2, 5], [5, 9]]
Output: [1, 0, 0, 1]
Explanation: Lets process all the queries one by one:
-> [0, 10]: The substring is "abaaabaaaba" which is a palindrome.
-> [5, 8]: The substring is "baaa" which is not a palindrome.
-> [2, 5]: The substring is “aaab” which is not a palindrome. 
-> [5, 9]: The substring is “baaab” which is a palindrome. 

Input: s = "abdcaaa", queries[][] = [[0, 1], [2, 2], [4, 6]]
Output: [0, 1, 1]
Explanation: Lets process all the queries one by one:
-> [0, 1]: The substring is "ab" which is not a palindrome.
-> [2, 2]: The substring is "d" which is a palindrome.
-> [4, 6]: The substring is “aaa” which is a palindrome. 

[Naive Approach] Brute Force Palindrome Check - O(n * q) Time and O(1) Space

The idea is for each query, extract the substring boundaries and check if it is a palindrome using two pointers one from the start and one from the end.
This approach compares characters directly for each query without any preprocessing or optimization.

C++
#include <iostream>
#include <vector>
using namespace std;

// function to check if a substring is a palindrome
bool isPalindrome(string &s, int start, int end) {
    while (start < end) {
        if (s[start] != s[end]) {
            return false;
        }
        start++;
        end--;
    }
    return true;
}

// function to check if the substring 
// is a palindrome for each query
vector<int> palQueries(string &s, 
    vector<vector<int>>& queries) {

    // to store the results
    vector<int> result;
    for (auto query : queries) {
        int start = query[0];
        int end = query[1];

        // check if the substring is a palindrome
        if (isPalindrome(s, start, end)) {
            result.push_back(1);
        } else {
            result.push_back(0);
        }
    }
    return result;
}

int main() {
    string s = "abaaabaaaba";
    vector<vector<int>> queries = 
        {{0, 10}, {5, 8}, {2, 5}, {5, 9}};
    vector<int> res = 
        palQueries(s, queries);
    for(auto i: res) {
        cout << i << " ";
    }
    return 0;
}
Java
import java.util.ArrayList;

public class GfG {

    // function to check if a substring is a palindrome
    static boolean isPalindrome(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }

    // function to check if the substring 
    // is a palindrome for each query
    static ArrayList<Integer> palQueries(String s, int[][] queries) {

        // to store the results
        ArrayList<Integer> result = new ArrayList<>();
        for (int[] query : queries) {
            int start = query[0];
            int end = query[1];

            // check if the substring is a palindrome
            if (isPalindrome(s, start, end)) {
                result.add(1);
            } else {
                result.add(0);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "abaaabaaaba";

        // define the queries using 2D array
        int[][] queries = {
            {0, 10},
            {5, 8},
            {2, 5},
            {5, 9}
        };

        ArrayList<Integer> res = palQueries(s, queries);

        for (int i : res) {
            System.out.print(i + " ");
        }
    }
}
Python
# function to check if a substring is a palindrome
def isPalindrome(s, start, end):
    while start < end:
        if s[start] != s[end]:
            return False
        start += 1
        end -= 1
    return True

# function to check if the substring 
# is a palindrome for each query
def palQueries(s, queries):

    # to store the results
    result = []
    for query in queries:
        start = query[0]
        end = query[1]

        # check if the substring is a palindrome
        if isPalindrome(s, start, end):
            result.append(1)
        else:
            result.append(0)
    return result

if __name__ == "__main__":
    s = "abaaabaaaba"
    queries = [[0, 10], [5, 8], [2, 5], [5, 9]]
    res = palQueries(s, queries)
    print(" ".join(map(str, res)))
C#
using System;
using System.Collections.Generic;

public class GfG {

    // function to check if a substring is a palindrome
    static bool isPalindrome(string s, int start, int end) {
        while (start < end) {
            if (s[start] != s[end]) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }

    // function to check if the substring 
    // is a palindrome for each query
    static List<int> palQueries(string s, int[][] queries) {

        // to store the results
        List<int> result = new List<int>();
        foreach (var query in queries) {
            int start = query[0];
            int end = query[1];

            // check if the substring is a palindrome
            if (isPalindrome(s, start, end)) {
                result.Add(1);
            } else {
                result.Add(0);
            }
        }
        return result;
    }

    public static void Main(string[] args) {
        string s = "abaaabaaaba";

        int[][] queries = new int[][] {
            new int[] {0, 10},
            new int[] {5, 8},
            new int[] {2, 5},
            new int[] {5, 9}
        };

        List<int> res = palQueries(s, queries);
        Console.WriteLine(string.Join(" ", res));
    }
}
JavaScript
// function to check if a substring is a palindrome
function isPalindrome(s, start, end) {
    while (start < end) {
        if (s[start] !== s[end]) {
            return false;
        }
        start++;
        end--;
    }
    return true;
}

// function to check if the substring 
// is a palindrome for each query
function palQueries(s, queries) {

    // to store the results
    let result = [];
    for (let query of queries) {
        let start = query[0];
        let end = query[1];

        // check if the substring is a palindrome
        if (isPalindrome(s, start, end)) {
            result.push(1);
        } else {
            result.push(0);
        }
    }
    return result;
}

// Driver Code
let s = "abaaabaaaba";
let queries = [[0, 10], [5, 8], [2, 5], [5, 9]];
let res = palQueries(s, queries);
console.log(res.join(" "));

Output
1 0 0 1 

[Expected Approach 1] Using Rabin-Karp Rolling Hash

The idea is to use Rabin-Karp’s rolling hash to efficiently check if a substring is a palindrome. We first precompute prefix hashes of the original string s and its reversed version revS. For each query [l, r], we compute the hash of s[l...r] and compare it to the hash of the corresponding substring in revS, which is revS[n - 1 - r ... n - 1 - l], where n is the length of s. If the two hash values are equal, the substring is a palindrome.

Definition: What Does preHash[i] Store ?

preHash[i] stores the hash of the prefix substring input[0 ... i-1] using both base values (base1 and base2).

Mathematically, for both bases:
=> preHash[i][0] = hash of input[0 to i-1] using base1
=> preHash[i][1] = hash of input[0 to i-1] using base2

The hash is computed as: Hash[i] = (input[0] x base^i−1 + input[1] x base^i−2 + .... + input[i−1] x base^0 ) % mod

This is built incrementally using the recurrence:
=> preHash[i + 1][0] = (preHash[i][0] * base1 + input[i]) % mod
=> preHash[i + 1][1] = (preHash[i][1] * base2 + input[i]) % mod

Substring Hash Formula (from getHash method):

To get the hash of the substring from index left to right - 1:
hash = (preHash[right][k] - preHash[left][k] x power[right−left][k]) % mod
=> where k = 0 for base1 and k = 1 for base2
=> So getHash(left, right) returns a pair of hashes: one using base1, one using base2.

For Palindrome Checking:

  • To check if s[l...r] is a palindrome:
  • Build two RollingHash objects — one for s, one for revS
  • Map [l, r] in s to [n - 1 - r, n - 1 - l] in revS
  • Compare getHash(l, r + 1) of s with getHash(n - 1 - r, n - l) of revS
  • If both base1 and base2 hashes match ⇒ substring is a palindrome

Step by Step Implementation:

  1. Create revS by reversing s.
  2. Initialize a RollingHash object for the original string s.
  3. Initialize a RollingHash object for the reversed string revS.
  4. For each query [left, right], define the substring as s[left...right].
  5. Compute the hash of s[left...right] using getHash(left, right + 1) on the s rolling hash.
  6. Compute revLeft = n - 1 - right, where n is the length of s.
  7. Compute revRight = n - left.
  8. Compute the hash of revS[revLeft...revRight - 1] using getHash(revLeft, revRight) on the revS rolling hash.
  9. Compare the two hashes from step 6 and step 9 for both base1 and base2.
  10. If both hashes match, then s[left...right] is a palindrome.
  11. If the hashes do not match, then s[left...right] is not a palindrome.
  12. Repeat steps 4 to 11 for all queries.
C++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

class RollingHash {
public:
    const int mod = 1e9 + 7;
    const int base1 = 31;
    const int base2 = 37;

    int length;
    string input;
    vector<vector<int>> preHash;
    vector<vector<int>> power;

    RollingHash(string& str) {
        input = str;
        length = input.size();
        preHash.assign(length + 1, vector<int>(2, 0));
        power.assign(length + 1, vector<int>(2, 1));
        buildHashes();
    }

    int add(int a, int b) {
        return (a + b) % mod;
    }

    int subtract(int a, int b) {
        return (a - b + mod) % mod;
    }

    int multiply(int a, int b) {
        return (1LL * a * b) % mod;
    }

    void buildHashes() {
        for (int i = 0; i < length; i++) {
            preHash[i + 1][0] = 
                add(multiply(preHash[i][0], base1), input[i]);
            preHash[i + 1][1] = 
                add(multiply(preHash[i][1], base2), input[i]);

            power[i + 1][0] = 
                multiply(power[i][0], base1);
            power[i + 1][1] = 
                multiply(power[i][1], base2);
        }
    }

    // get hash of input[left...right-1]
    vector<int> getHash(int left, int right) {
        vector<int> result(2);
        for (int b = 0; b < 2; ++b) {
            result[b] = 
                subtract(preHash[right][b], 
                    multiply(preHash[left][b], power[right - left][b]));
        }
        return result;
    }
};

// function to check palindromes using rolling hash
vector<int> palQueries(string s, vector<vector<int>>& queries) {
    int n = s.size();
    string revS = s;
    reverse(revS.begin(), revS.end());

    RollingHash forwardHash(s);
    RollingHash reverseHash(revS);
    vector<int> result;

    for (auto& q : queries) {
        int left = q[0];
        int right = q[1];

        // get hash of s[left...right]
        vector<int> h1 = forwardHash.getHash(left, right + 1);

        // map to reversed string: revS[n-1-right ... n-1-left]
        int revLeft = n - 1 - right;
        int revRight = n - left;
        vector<int> h2 = reverseHash.getHash(revLeft, revRight);

        if (h1 == h2) {
            result.push_back(1);
        } else {
            result.push_back(0);
        }
    }
    return result;
}

int main() {
    string str = "abaaabaaaba";
    vector<vector<int>> queries = {{0, 10}, {5, 8}, {2, 5}, {5, 9}};
    vector<int> res = palQueries(str, queries);

    for (auto i : res) {
        cout << i << " ";
    }
    return 0;
}
Java
import java.util.ArrayList;

class GfG {

    static class RollingHash {
        final int mod = 1000000007;
        final int base1 = 31;
        final int base2 = 37;

        int length;
        String input;
        int[][] preHash;
        int[][] power;

        RollingHash(String str) {
            input = str;
            length = input.length();
            preHash = new int[length + 1][2];
            power = new int[length + 1][2];
            power[0][0] = power[0][1] = 1;
            buildHashes();
        }

        int add(int a, int b) {
            return (a + b) % mod;
        }

        int subtract(int a, int b) {
            return (a - b + mod) % mod;
        }

        int multiply(int a, int b) {
            return (int)((1L * a * b) % mod);
        }

        void buildHashes() {
            for (int i = 0; i < length; i++) {
                preHash[i + 1][0] = 
                    add(multiply(preHash[i][0], base1), input.charAt(i));
                preHash[i + 1][1] = 
                    add(multiply(preHash[i][1], base2), input.charAt(i));

                power[i + 1][0] = multiply(power[i][0], base1);
                power[i + 1][1] = multiply(power[i][1], base2);
            }
        }

        // get hash of input[left...right-1]
        int[] getHash(int left, int right) {
            int[] result = new int[2];
            for (int k = 0; k < 2; k++) {
                result[k] = 
                    subtract(preHash[right][k], 
                        multiply(preHash[left][k], power[right - left][k]));
            }
            return result;
        }
    }

    // function to check palindromes using rolling hash
    public static ArrayList<Integer> palQueries(String s, int[][] queries) {
        int n = s.length();
        String revS = new StringBuilder(s).reverse().toString();

        RollingHash forwardHash = new RollingHash(s);
        RollingHash reverseHash = new RollingHash(revS);
        ArrayList<Integer> result = new ArrayList<>();

        for (int[] q : queries) {
            int left = q[0];
            int right = q[1];

            // get hash of s[left...right]
            int[] h1 = forwardHash.getHash(left, right + 1);

            // map to reversed string: revS[n-1-right ... n-1-left]
            int revLeft = n - 1 - right;
            int revRight = n - left;
            int[] h2 = reverseHash.getHash(revLeft, revRight);

            if (h1[0] == h2[0] && h1[1] == h2[1]) {
                result.add(1);
            } else {
                result.add(0);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String str = "abaaabaaaba";
        int[][] queries = {{0, 10}, {5, 8}, {2, 5}, {5, 9}};
        ArrayList<Integer> res = palQueries(str, queries);
        for (int val : res) {
            System.out.print(val + " ");
        }
    }
}
Python
def buildRollingHash(string, base1, base2, mod):
    n = len(string)
    preHash = [[0, 0] for _ in range(n + 1)]
    power = [[1, 1] for _ in range(n + 1)]

    for i in range(n):
        preHash[i + 1][0] =\
            (preHash[i][0] * base1 + ord(string[i])) % mod
        preHash[i + 1][1] = \
            (preHash[i][1] * base2 + ord(string[i])) % mod

        power[i + 1][0] = \
            (power[i][0] * base1) % mod
        power[i + 1][1] = \
            (power[i][1] * base2) % mod

    return preHash, power

def getHash(preHash, power, left, right, mod):
    return [
        (preHash[right][k] - preHash[left][k] * 
                power[right - left][k] % mod + mod) % mod
        for k in range(2)
    ]


# function to check palindromes using rolling hash
def palQueries(s, queries):
    mod = int(1e9 + 7)
    base1 = 31
    base2 = 37
    n = len(s)
    revS = s[::-1]

    # build hashes for original and reversed strings
    preHashF, powerF = \
        buildRollingHash(s, base1, base2, mod)
    preHashR, powerR = \
        buildRollingHash(revS, base1, base2, mod)

    result = []

    for left, right in queries:
        # get hash of s[left...right]
        h1 = getHash(preHashF, powerF, left, right + 1, mod)

        # map to reversed string: revS[n-1-right ... n-1-left]
        revLeft = n - 1 - right
        revRight = n - left
        h2 = getHash(preHashR, powerR, revLeft, revRight, mod)

        result.append(1 if h1 == h2 else 0)

    return result
    
if __name__ == "__main__":
    s = "abaaabaaaba"
    queries = [[0, 10], [5, 8], [2, 5], [5, 9]]
    res = palQueries(s, queries)
    print(*res)
C#
using System;
using System.Collections.Generic;

class GfG {

    class RollingHash {
        private const int mod = 1000000007;
        private const int base1 = 31;
        private const int base2 = 37;

        private int length;
        private string input;
        private int[][] preHash;
        private int[][] power;

        public RollingHash(string str) {
            input = str;
            length = input.Length;
            preHash = new int[length + 1][];
            power = new int[length + 1][];
            for (int i = 0; i <= length; i++) {
                preHash[i] = new int[2];
                power[i] = new int[] {1, 1};
            }
            buildHashes();
        }

        private int add(int a, int b) {
            return (a + b) % mod;
        }

        private int subtract(int a, int b) {
            return (a - b + mod) % mod;
        }

        private int multiply(int a, int b) {
            return (int)((long)a * b % mod);
        }

        private void buildHashes() {
            for (int i = 0; i < length; i++) {
                preHash[i + 1][0] = add(multiply(preHash[i][0], base1), input[i]);
                preHash[i + 1][1] = add(multiply(preHash[i][1], base2), input[i]);

                power[i + 1][0] = multiply(power[i][0], base1);
                power[i + 1][1] = multiply(power[i][1], base2);
            }
        }

        // get hash of input[left...right-1]
        public int[] GetHash(int left, int right) {
            int[] result = new int[2];
            for (int k = 0; k < 2; k++) {
                result[k] = 
                    subtract(preHash[right][k], 
                        multiply(preHash[left][k], power[right - left][k]));
            }
            return result;
        }
    }

    // function to check palindromes using rolling hash
    public static List<int> palQueries(string s, int[][] queries) {
        int n = s.Length;
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        string revS = new string(arr);

        RollingHash forwardHash = new RollingHash(s);
        RollingHash reverseHash = new RollingHash(revS);
        List<int> result = new List<int>();

        foreach (var q in queries) {
            int left = q[0];
            int right = q[1];

            // get hash of s[left...right]
            int[] h1 = forwardHash.GetHash(left, right + 1);

            // map to reversed string: revS[n-1-right ... n-1-left]
            int revLeft = n - 1 - right;
            int revRight = n - left;
            int[] h2 = reverseHash.GetHash(revLeft, revRight);

            if (h1[0] == h2[0] && h1[1] == h2[1]) {
                result.Add(1);
            } else {
                result.Add(0);
            }
        }
        return result;
    }

    static void Main() {
        string str = "abaaabaaaba";
        int[][] queries = new int[][] {
            new int[] {0, 10}, new int[] {5, 8},
            new int[] {2, 5}, new int[] {5, 9}
        };
        List<int> res = palQueries(str, queries);
        Console.WriteLine(string.Join(" ", res));
    }
}
JavaScript
/*---- Rabin Karp Algorithm Start ----*/

// function to initialize and build rolling hash data
function buildRollingHash(str, base1, base2, mod) {
    const length = str.length;
    const preHash = 
        Array.from({ length: length + 1 }, () => [0n, 0n]);
    const power = 
        Array.from({ length: length + 1 }, () => [1n, 1n]);

    for (let i = 0; i < length; i++) {
        preHash[i + 1][0] = 
            (preHash[i][0] * base1 + 
                            BigInt(str.charCodeAt(i))) % mod;
        preHash[i + 1][1] = 
            (preHash[i][1] * base2 + 
                            BigInt(str.charCodeAt(i))) % mod;

        power[i + 1][0] = (power[i][0] * base1) % mod;
        power[i + 1][1] = (power[i][1] * base2) % mod;
    }

    return { preHash, power };
}

// function to get hash of substring input[left...right-1]
function getHash(preHash, power, left, right, mod) {
    return [0, 1].map(k =>
        (preHash[right][k] - (preHash[left][k] * 
                                    power[right - left][k]) 
                                            % mod + mod) % mod
    );
}
/*---- Rabin Karp Algorithm End ----*/


// function to check palindromes using rolling hash
function palQueries(s, queries) {
    const mod = 1000000007n;
    const base1 = 31n;
    const base2 = 37n;
    const n = s.length;
    const revS = s.split("").reverse().join("");

    // build rolling hashes for both original and reversed string
    const forward = buildRollingHash(s, base1, base2, mod);
    const reverse = buildRollingHash(revS, base1, base2, mod);

    const result = [];

    for (const [left, right] of queries) {
        // get hash of s[left...right]
        const h1 = getHash(forward.preHash, 
                        forward.power, left, right + 1, mod);

        // map to reversed string: revS[n-1-right ... n-1-left]
        const revLeft = n - 1 - right;
        const revRight = n - left;
        const h2 = getHash(reverse.preHash, 
                        reverse.power, revLeft, revRight, mod);

        // compare both hashes
        if (h1[0] === h2[0] && h1[1] === h2[1]) {
            result.push(1);
        } else {
            result.push(0);
        }
    }

    return result;
}

// Driver Code
const str = "abaaabaaaba";
const queries = [[0, 10], [5, 8], [2, 5], [5, 9]];
console.log(palQueries(str, queries).join(" "));

Output
1 0 0 1 

Time Complexity: O(n + q), O(n) to precompute prefix hashes and powers, and O(1) for each of the q queries.
Auxiliary Space: O(n)

[Expected Approach 2] Manacher’s Algorithm for Palindromic Substrings

The idea is to use Manacher's Algorithm to preprocess the input string and compute the length of the longest palindromic substring centered at each position.
By inserting separators (like #) between characters, the algorithm uniformly handles even and odd length palindromes.
After preprocessing, for each query [l, r], we map the original indices to the modified string and check if the palindrome radius at the center covers the full substring length.
This allows us to answer each palindrome query in O(1) time after an O(n) preprocessing.

Step by Step Implementation:

  • Preprocess the string by inserting # between every character and adding special sentinels at both ends (@ at the start and $ at the end).
    Example: s = "aba" → ms = "@#a#b#a#$"
  • Run Manacher’s algorithm on this modified string to compute the array p[], where p[i] stores the maximum radius of the palindrome centered at index i in the modified string.
  • For each query [l, r]:
    => Calculate the length of the original substring: len = r - l + 1
    => Convert the original center index to modified string's center: center = l + r + 2 (offset due to inserted # and starting @)
  • Check if the value of p[center] ≥ len. This confirms that the substring s[l..r] is fully covered by the palindrome radius from the center.
  • Return 1 if it's a palindrome, otherwise return 0.
C++
#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Manacher {
public:
    vector<int> p;
    string ms;

    Manacher(string &s) {
        
        // build modified string with sentinels and separators
        ms = "@";
        for (char c : s) ms += "#" + string(1, c);
        ms += "#$";
        runManacher();
    }

    void runManacher() {
        int n = ms.size();
        p.assign(n, 0);

        int left = 0, right = 0;

        for (int i = 1; i < n - 1; ++i) {
            int mirror = left + right - i;

            // initialize radius using mirror or boundary
            if (i < right) p[i] = min(right - i, p[mirror]);

            // expand around i
            while (ms[i + p[i] + 1] == ms[i - p[i] - 1])
                ++p[i];

            // update left and right bounds
            if (i + p[i] > right) {
                left = i - p[i];
                right = i + p[i];
            }
        }
    }

    bool isPalindrome(int l, int r) {
        
        // compute the center index 
        // in modified string
        int mid = l + r + 2;
        int len = r - l + 1;

        // check if radius covers the length
        return p[mid] >= len;
    }
};


vector<int> palQueries(string &s, 
        vector<vector<int>> &queries){
    
    Manacher M(s);
    
    vector<int> res;

    for (auto& query : queries) {
        int l = query[0], r = query[1];
        res.push_back(M.isPalindrome(l, r));
    }
    
    return res;
}

int main() {
    
    string str = "abaaabaaaba";
    vector<vector<int>> queries = 
            {{0, 10}, {5, 8}, {2, 5}, {5, 9}};
    vector<int> res = palQueries(str, queries);

    for (auto i : res) {
        cout << i << " ";
    }
    return 0;
}
Java
import java.util.*;

class GfG {

    static class Manacher {
        int[] p;
        String ms;

        Manacher(String s) {
            // build modified string with 
            //  sentinels and separators
            StringBuilder sb = 
                new StringBuilder("@");
            for (char c : s.toCharArray()) {
                sb.append("#").append(c);
            }
            sb.append("#$");
            ms = sb.toString();
            runManacher();
        }

        void runManacher() {
            int n = ms.length();
            p = new int[n];
            int left = 0, right = 0;

            for (int i = 1; i < n - 1; i++) {
                int mirror = left + right - i;

                // initialize radius using mirror or boundary
                if (i < right) p[i] = 
                        Math.min(right - i, p[mirror]);

                // expand around i
                while (ms.charAt(i + p[i] + 1) 
                            == ms.charAt(i - p[i] - 1))
                    p[i]++;

                // update left and right bounds
                if (i + p[i] > right) {
                    left = i - p[i];
                    right = i + p[i];
                }
            }
        }

        boolean isPalindrome(int l, int r) {
            // compute the center index in 
            // modified string
            int mid = l + r + 2;
            int len = r - l + 1;

            // check if radius covers the length
            return p[mid] >= len;
        }
    }

    public static ArrayList<Integer> palQueries(String s, 
                                        int[][] queries) {
        Manacher M = new Manacher(s);
        ArrayList<Integer> res = new ArrayList<>();

        for (int[] query : queries) {
            int l = query[0], r = query[1];
            res.add(M.isPalindrome(l, r) ? 1 : 0);
        }
        return res;
    }

    public static void main(String[] args) {
        String str = "abaaabaaaba";
        int[][] queries = 
                    {{0, 10}, {5, 8}, {2, 5}, {5, 9}};
        ArrayList<Integer> res = palQueries(str, queries);
        for (int x : res) System.out.print(x + " ");
    }
}
Python
''' Manacher's Algorithm Starts ''' 

def buildManacher(s):
    # build modified string with sentinels and separators
    ms = '@' + '#'.join([''] + list(s)) + '#$'
    n = len(ms)
    p = [0] * n
    left = right = 0

    for i in range(1, n - 1):
        mirror = left + right - i

        # initialize radius using mirror or boundary
        if i < right:
            p[i] = min(right - i, p[mirror])

        # expand around i
        while ms[i + p[i] + 1] == ms[i - p[i] - 1]:
            p[i] += 1

        # update left and right bounds
        if i + p[i] > right:
            left = i - p[i]
            right = i + p[i]
    return p, ms

def isPalindrome(l, r, p):
    # compute the center index in modified string
    mid = l + r + 2
    length = r - l + 1

    # check if radius covers the length
    return p[mid] >= length

''' Manacher's Algorithm Ends ''' 

def palQueries(s, queries):
    p, ms = buildManacher(s)
    res = []
    for l, r in queries:
        res.append(1 if isPalindrome(l, r, p) else 0)
    return res

if __name__ == "__main__":
    str_ = "abaaabaaaba"
    queries = [[0, 10], [5, 8], [2, 5], [5, 9]]
    res = palQueries(str_, queries)
    print(' '.join(map(str, res)))
C#
using System;
using System.Collections.Generic;

class GfG {
    class Manacher {
        public int[] p;
        string ms;

        public Manacher(string s) {
            // build modified string with 
            // sentinels and separators
            ms = "@";
            foreach (char c in s) ms += "#" + c;
            ms += "#$";
            runManacher();
        }

        void runManacher() {
            int n = ms.Length;
            p = new int[n];
            int left = 0, right = 0;

            for (int i = 1; i < n - 1; i++) {
                int mirror = left + right - i;

                // initialize radius using mirror or boundary
                if (i < right) p[i] = 
                    Math.Min(right - i, p[mirror]);

                // expand around i
                while (ms[i + p[i] + 1] == ms[i - p[i] - 1])
                    p[i]++;

                // update left and right bounds
                if (i + p[i] > right) {
                    left = i - p[i];
                    right = i + p[i];
                }
            }
        }

        public bool isPalindrome(int l, int r) {
            // compute the center index in modified string
            int mid = l + r + 2;
            int len = r - l + 1;

            // check if radius covers the length
            return p[mid] >= len;
        }
    }

    static List<int> palQueries(string s,
                        List<List<int>> queries) {
        var M = new Manacher(s);
        List<int> res = new List<int>();
        foreach (var q in queries)
            res.Add(M.isPalindrome(q[0], q[1]) ? 1 : 0);
        return res;
    }

    static void Main() {
        string str = "abaaabaaaba";
        var queries = new List<List<int>> {
            new List<int>{0, 10}, new List<int>{5, 8},
            new List<int>{2, 5}, new List<int>{5, 9}
        };
        var res = palQueries(str, queries);
        Console.WriteLine(string.Join(" ", res));
    }
}
JavaScript
/* Manacher's Algorithm Ends */

// function to build Manacher's array
function buildManacher(s) {
    // build modified string with sentinels 
    //  and separators
    let ms = '@#' + s.split('').join('#') + '#$';
    const p = Array(ms.length).fill(0);
    let left = 0, right = 0;

    for (let i = 1; i < ms.length - 1; i++) {
        let mirror = left + right - i;

        // initialize radius using mirror or boundary
        if (i < right) p[i] = 
                        Math.min(right - i, p[mirror]);

        // expand around i
        while (ms[i + p[i] + 1] === ms[i - p[i] - 1])
                p[i]++;

        // update left and right bounds
        if (i + p[i] > right) {
            left = i - p[i];
            right = i + p[i];
        }
    }
    return p;
}

function isPalindrome(l, r, p) {
    // compute the center index in modified string
    let mid = l + r + 2;
    let len = r - l + 1;

    // check if radius covers the length
    return p[mid] >= len;
}

/* Manacher's Algorithm Ends */

function palQueries(s, queries) {
    const p = buildManacher(s);
    const res = [];

    for (const [l, r] of queries) {
        res.push(isPalindrome(l, r, p) ? 1 : 0);
    }
    return res;
}

// Driver Code
const str = "abaaabaaaba";
const queries = [[0, 10], [5, 8], [2, 5], [5, 9]];
console.log(palQueries(str, queries).join(' '));

Output
1 0 0 1 

Time Complexity: O(n + q), manacher's algorithm runs in linear time O(n) due to clever use of symmetry and previous computations. Each query check is constant time.
Auxiliary Space: O(n), because we store a modified version of the string (ms) and a radius array (p[]), both proportional to the input size.


Similar Reads