VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-palindromic-substrings-in-an-index-range/

⇱ Count of Palindromic substrings in an Index range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of Palindromic substrings in an Index range

Last Updated : 23 Jul, 2025

Given a string str of small alphabetic characters other than this we will be given many substrings of this string in form of index tuples. We need to find out the count of the palindromic substrings in given substring range. 

Examples: 

Input : String str = "xyaabax"
 Range1 = (3, 5) 
 Range2 = (2, 3) 
Output : 4
 3
For Range1, substring is "aba"
Count of palindromic substring in "aba" is 
four : "a", "b", "aba", "a"
For Range2, substring is "aa"
Count of palindromic substring in "aa" is 
3 : "a", "a", "aa"

Prerequisite : Count All Palindrome Sub-Strings in a String

We can solve this problem using dynamic programming. First we will make a 2D array isPalin, isPalin[i][j] will be 1 if string(i..j) is a palindrome otherwise it will be 0. After constructing isPalin we will construct another 2D array dp, dp[i][j] will tell the count of palindromic substring in string(i..j) 

Now we can write the relation among isPalin and dp values as shown below, 

// isPalin[i][j] will be 1 if ith and jth characters 
// are equal and mid substring str(i+1..j-1) is also
// a palindrome
isPalin[i][j] = (str[i] == str[j]) and 
 (isPalin[i + 1][j – 1])
 
// Similar to set theory we can write the relation among
// dp values as,
// dp[i][j] will be addition of number of palindromes from 
// i to j-1 and i+1 to j subtracting palindromes from i+1
// to j-1 because they are counted twice once in dp[i][j-1] 
// and then in dp[i + 1][j] plus 1 if str(i..j) is also a
// palindrome
dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1] + 
 isPalin[i][j];


Total time complexity of solution will be O(length ^ 2) for constructing dp array then O(1) per query. 


Output
4

Time complexity : O(l2
Auxiliary Space : O(l2)

Comment
Article Tags: