Palindrome Substring Queries
Last Updated :
29 Jul, 2025
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(" "));
[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:
- Create revS by reversing s.
- Initialize a RollingHash object for the original string s.
- Initialize a RollingHash object for the reversed string revS.
- For each query [left, right], define the substring as s[left...right].
- Compute the hash of s[left...right] using getHash(left, right + 1) on the s rolling hash.
- Compute revLeft = n - 1 - right, where n is the length of s.
- Compute revRight = n - left.
- Compute the hash of revS[revLeft...revRight - 1] using getHash(revLeft, revRight) on the revS rolling hash.
- Compare the two hashes from step 6 and step 9 for both base1 and base2.
- If both hashes match, then s[left...right] is a palindrome.
- If the hashes do not match, then s[left...right] is not a palindrome.
- 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(" "));
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(' '));
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
Basics & Prerequisites
Data Structures
Array Data StructureIn 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