Related Articles

# Queries to check if substring[L…R] is palindrome or not

• Difficulty Level : Medium
• Last Updated : 21 May, 2021

Given a string str and Q queries. Every query consists of two numbers L and R. The task is to print if the sub-string[L…R] is palindrome or not.

Examples:

Input: str = “abacccde”, Q[][] = {{0, 2}, {1, 2}, {2, 4}, {3, 5}}
Output:
Yes
No
No
Yes

Input: str = “abaaab”, Q[][] = {{0, 1}, {1, 5}}
Output:
No
Yes

Simple Approach: A naive approach is to check for every sub-string if it is palindrome or not. In the worst case, every query can take up to O(Q).

Efficient Approach: An efficient approach is to use Dynamic Programming to solve the above problem. We can initially create the DP table which stores if substring[i….j] is palindrome or not. We maintain a boolean dp[n][n] that is filled in a bottom-up manner. The value of dp[i][j] is true if the substring is a palindrome, otherwise false. To calculate dp[i][j], we first check the value of dp[i+1][j-1], if the value is true and s[i] is the same as s[j], then we make dp[i][j] true. Otherwise, the value of dp[i][j] is made false.
Now, for every query, check if dp[l][r] is true or not.

Below is the implementation of the above approach:

## C++

 `// C++ implementation of the approach``#include ``using` `namespace` `std;``#define N 100` `// Pre-processing function``void` `pre_process(``bool` `dp[N][N], string s)``{` `    ``// Get the size of the string``    ``int` `n = s.size();` `    ``// Initially mark every``    ``// position as false``    ``for` `(``int` `i = 0; i < n; i++) {``        ``for` `(``int` `j = 0; j < n; j++)``            ``dp[i][j] = ``false``;``    ``}` `    ``// For the length``    ``for` `(``int` `j = 1; j <= n; j++) {` `        ``// Iterate for every index with``        ``// length j``        ``for` `(``int` `i = 0; i <= n - j; i++) {` `            ``// If the length is less than 2``            ``if` `(j <= 2) {` `                ``// If characters are equal``                ``if` `(s[i] == s[i + j - 1])``                    ``dp[i][i + j - 1] = ``true``;``            ``}` `            ``// Check for equal``            ``else` `if` `(s[i] == s[i + j - 1])``                ``dp[i][i + j - 1] = dp[i + 1][i + j - 2];``        ``}``    ``}``}` `// Function to answer every query in O(1)``void` `answerQuery(``int` `l, ``int` `r, ``bool` `dp[N][N])``{``    ``if` `(dp[l][r])``        ``cout << ``"Yes\n"``;``    ``else``        ``cout << ``"No\n"``;``}` `// Driver code``int` `main()``{``    ``string s = ``"abaaab"``;``    ``bool` `dp[N][N];``    ``pre_process(dp, s);` `    ``int` `queries[] = { { 0, 1 }, { 1, 5 } };``    ``int` `q = ``sizeof``(queries) / ``sizeof``(queries);` `    ``for` `(``int` `i = 0; i < q; i++)``        ``answerQuery(queries[i], queries[i], dp);` `    ``return` `0;``}`

## Java

 `// Java implementation of the approach``class` `GFG {` `    ``static` `int` `N = ``100``;` `    ``// Pre-processing function``    ``static` `void` `pre_process(``boolean` `dp[][], ``char``[] s)``    ``{` `        ``// Get the size of the string``        ``int` `n = s.length;` `        ``// Initially mark every``        ``// position as false``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``for` `(``int` `j = ``0``; j < n; j++) {``                ``dp[i][j] = ``false``;``            ``}``        ``}` `        ``// For the length``        ``for` `(``int` `j = ``1``; j <= n; j++) {` `            ``// Iterate for every index with``            ``// length j``            ``for` `(``int` `i = ``0``; i <= n - j; i++) {` `                ``// If the length is less than 2``                ``if` `(j <= ``2``) {` `                    ``// If characters are equal``                    ``if` `(s[i] == s[i + j - ``1``]) {``                        ``dp[i][i + j - ``1``] = ``true``;``                    ``}``                ``}` `                ``// Check for equal``                ``else` `if` `(s[i] == s[i + j - ``1``]) {``                    ``dp[i][i + j - ``1``] = dp[i + ``1``][i + j - ``2``];``                ``}``            ``}``        ``}``    ``}` `    ``// Function to answer every query in O(1)``    ``static` `void` `answerQuery(``int` `l, ``int` `r, ``boolean` `dp[][])``    ``{``        ``if` `(dp[l][r]) {``            ``System.out.println(``"Yes"``);``        ``}``        ``else` `{``            ``System.out.println(``"No"``);``        ``}``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``String s = ``"abaaab"``;``        ``boolean``[][] dp = ``new` `boolean``[N][N];``        ``pre_process(dp, s.toCharArray());` `        ``int` `queries[][] = { { ``0``, ``1` `}, { ``1``, ``5` `} };``        ``int` `q = queries.length;` `        ``for` `(``int` `i = ``0``; i < q; i++) {``            ``answerQuery(queries[i][``0``], queries[i][``1``], dp);``        ``}``    ``}``}` `// This code contributed by Rajput-Ji`

## Python3

 `# Python3 implementation of the approach``N ``=` `100` `# Pre-processing function``def` `pre_process(dp, s):` `    ``# Get the size of the string``    ``n ``=` `len``(s)` `    ``# Initially mark every``    ``# position as false``    ``for` `i ``in` `range``(n):``        ``for` `j ``in` `range``(n):``            ``dp[i][j] ``=` `False` `    ``# For the length``    ``for` `j ``in` `range``(``1``, n ``+` `1``):` `        ``# Iterate for every index with``        ``# length j``        ``for` `i ``in` `range``(n ``-` `j ``+` `1``):` `            ``# If the length is less than 2``            ``if` `(j <``=` `2``):` `                ``# If characters are equal``                ``if` `(s[i] ``=``=` `s[i ``+` `j ``-` `1``]):``                    ``dp[i][i ``+` `j ``-` `1``] ``=` `True` `            ``# Check for equal``            ``elif` `(s[i] ``=``=` `s[i ``+` `j ``-` `1``]):``                ``dp[i][i ``+` `j ``-` `1``] ``=` `dp[i ``+` `1``][i ``+` `j ``-` `2``]` `# Function to answer every query in O(1)``def` `answerQuery(l, r, dp):` `    ``if` `(dp[l][r]):``        ``print``(``"Yes"``)``    ``else``:``        ``print``(``"No"``)` `# Driver code``s ``=` `"abaaab"``dp ``=` `[[``0` `for` `i ``in` `range``(N)]``         ``for` `i ``in` `range``(N)]``pre_process(dp, s)` `queries ``=` `[[``0``, ``1``], [``1``, ``5``]]``q ``=` `len``(queries)` `for` `i ``in` `range``(q):``    ``answerQuery(queries[i][``0``],``                ``queries[i][``1``], dp)` `# This code is contributed by mohit kumar`

## C#

 `// C# implementation of the approach``using` `System;``class` `GFG {` `    ``static` `int` `N = 100;` `    ``// Pre-processing function``    ``static` `void` `pre_process(``bool``[, ] dp, ``char``[] s)``    ``{` `        ``// Get the size of the string``        ``int` `n = s.Length;` `        ``// Initially mark every``        ``// position as false``        ``for` `(``int` `i = 0; i < n; i++) {``            ``for` `(``int` `j = 0; j < n; j++) {``                ``dp[i, j] = ``false``;``            ``}``        ``}` `        ``// For the length``        ``for` `(``int` `j = 1; j <= n; j++) {` `            ``// Iterate for every index with``            ``// length j``            ``for` `(``int` `i = 0; i <= n - j; i++) {` `                ``// If the length is less than 2``                ``if` `(j <= 2) {` `                    ``// If characters are equal``                    ``if` `(s[i] == s[i + j - 1]) {``                        ``dp[i, i + j - 1] = ``true``;``                    ``}``                ``}` `                ``// Check for equal``                ``else` `if` `(s[i] == s[i + j - 1]) {``                    ``dp[i, i + j - 1] = dp[i + 1, i + j - 2];``                ``}``            ``}``        ``}``    ``}` `    ``// Function to answer every query in O(1)``    ``static` `void` `answerQuery(``int` `l, ``int` `r, ``bool``[, ] dp)``    ``{``        ``if` `(dp[l, r]) {``            ``Console.WriteLine(``"Yes"``);``        ``}``        ``else` `{``            ``Console.WriteLine(``"No"``);``        ``}``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{``        ``string` `s = ``"abaaab"``;``        ``bool``[, ] dp = ``new` `bool``[N, N];``        ``pre_process(dp, s.ToCharArray());` `        ``int``[, ] queries = { { 0, 1 }, { 1, 5 } };``        ``int` `q = queries.Length;` `        ``for` `(``int` `i = 0; i < q; i++) {``            ``answerQuery(queries[i, 0], queries[i, 1], dp);``        ``}``    ``}``}` `// This code is contributed by Ankit.`

## PHP

 ``

## Javascript

 ``
Output:
```No
Yes```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up