Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Find all Palindrome Strings in given Array of strings
Next article icon

All distinct palindromic sub-strings of a given string

Last Updated : 11 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a string str of lowercase ASCII characters. The task is to find all the distinct continuous palindromic sub-strings which are present in the string str.

Examples: 

Input: str = “abaaa”
Output: [ “a”, “aa”, “aaa”, “aba”, “b” ]
Explanation: All 5 distinct continuous palindromic sub-strings are listed above.

Input: str = “geek”
Output: [ “e”, “ee”, “g”, “k” ]
Explanation: All 4 distinct continuous palindromic sub-strings are listed above.

[Naive Approach – 1] – Generating All Substrings – O(n ^ 3) Time and O(n ^ 2) Space

The idea is to generate all possible substrings and find all the palindromic substrings, and use set to store all the distinct one.

C++
#include <bits/stdc++.h> using namespace std;  // Function to find all distinct palindrome  // substrings in a given string vector<string> palindromicSubstr(string &str) {     int n = str.length();      // Create a set to store the result     unordered_set<string> result;      // generate all substrings     for(int i = 0; i < n; i++) {          // to store the substring         string cur = "";          for(int j = i; j < n; j++) {             cur += str[j];              // check if cur is palindrome             int l = 0, r = cur.length() - 1;             bool isPalindrome = true;             while(l < r) {                 if(cur[l] != cur[r]) {                     isPalindrome = false;                     break;                 }                 l++;                 r--;             }              // if cur is palindrome,              // insert it into the set             if(isPalindrome) {                 result.insert(cur);             }         }     }      // Convert the set to a vector     vector<string> res(result.begin(), result.end());      return res; }  int main() {     string str = "abaaa";     vector<string> result = palindromicSubstr(str);     for(string s : result)         cout << s << " ";     return 0; } 
Java
// Function to find all distinct palindrome  // substrings in a given string import java.util.*;  class GfG {      // Function to find all distinct palindrome      // substrings in a given string     static ArrayList<String> palindromicSubstr(String str) {         int n = str.length();                  // Create a set to store the result         HashSet<String> result = new HashSet<>();                  // generate all substrings         for (int i = 0; i < n; i++) {                          // to store the substring             String cur = "";                          for (int j = i; j < n; j++) {                 cur += str.charAt(j);                                  // check if cur is palindrome                 int l = 0, r = cur.length() - 1;                 boolean isPalindrome = true;                 while (l < r) {                     if (cur.charAt(l) != cur.charAt(r)) {                         isPalindrome = false;                         break;                     }                     l++;                     r--;                 }                                  // if cur is palindrome,                  // insert it into the set                 if (isPalindrome) {                     result.add(cur);                 }             }         }                  // Convert the set to a vector         ArrayList<String> res = new ArrayList<>(result);                  return res;     }          public static void main(String[] args) {         String str = "abaaa";         ArrayList<String> result = palindromicSubstr(str);         for (String s : result)             System.out.print(s + " ");     } } 
Python
# Function to find all distinct palindrome  # substrings in a given string. def palindromicSubstr(str):     n = len(str)          # Create a set to store the result     result = set()          # generate all substrings     for i in range(n):         # to store the substring         cur = ""         for j in range(i, n):             cur += str[j]                          # check if cur is palindrome             l = 0             r = len(cur) - 1             isPalindrome = True             while l < r:                 if cur[l] != cur[r]:                     isPalindrome = False                     break                 l += 1                 r -= 1                          # if cur is palindrome,              # insert it into the set             if isPalindrome:                 result.add(cur)          # Convert the set to a vector     res = list(result)          return res  if __name__ == "__main__":     str = "abaaa"     result = palindromicSubstr(str)     for s in result:         print(s, end=" ") 
C#
// Function to find all distinct palindrome  // substrings in a given string using System; using System.Collections.Generic;  class GfG {      // Function to find all distinct palindrome      // substrings in a given string     static List<string> PalindromicSubstr(string str) {         int n = str.Length;                  // Create a set to store the result         HashSet<string> result = new HashSet<string>();                  // generate all substrings         for (int i = 0; i < n; i++) {                          // to store the substring             string cur = "";                          for (int j = i; j < n; j++) {                 cur += str[j];                                  // check if cur is palindrome                 int l = 0, r = cur.Length - 1;                 bool isPalindrome = true;                 while (l < r) {                     if (cur[l] != cur[r]) {                         isPalindrome = false;                         break;                     }                     l++;                     r--;                 }                                  // if cur is palindrome,                  // insert it into the set                 if (isPalindrome) {                     result.Add(cur);                 }             }         }                  // Convert the set to a list         List<string> res = new List<string>(result);                  return res;     }          public static void Main(string[] args) {         string str = "abaaa";         List<string> result = PalindromicSubstr(str);         foreach (string s in result)             Console.Write(s + " ");     } } 
JavaScript
// Function to find all distinct palindrome  // substrings in a given string. function palindromicSubstr(str) {     let n = str.length;          // Create a set to store the result     let result = new Set();          // generate all substrings     for (let i = 0; i < n; i++) {                  // to store the substring         let cur = "";         for (let j = i; j < n; j++) {             cur += str[j];                          // check if cur is palindrome             let l = 0, r = cur.length - 1;             let isPalindrome = true;             while (l < r) {                 if (cur[l] !== cur[r]) {                     isPalindrome = false;                     break;                 }                 l++;                 r--;             }                          // if cur is palindrome,              // insert it into the set             if (isPalindrome) {                 result.add(cur);             }         }     }          // Convert the set to a vector     let res = Array.from(result);          return res; }   let str = "abaaa"; let result = palindromicSubstr(str); console.log(result.join(" ")); 

Output
a aaa aba b aa 

[Naive Approach – 2] – Using Dynamic Programming and Set – O(n ^ 3) Time and O(n ^ 2) Space

The idea is to use Dynamic Programming to find all palindromic substrings and set to store all the distinct one. To do so, create a 2d array dp[][] of order n * n, where dp[i][j] is True if substring s[i..j] is palindrome. Any substring s[i..j] will be palindromic if s[i] == s[j] and dp[i+1][j-1] is True. Thus run a nested loop where the outer loop marks the start and inner loop marks the end of substring.

Follow the below given steps:

  • Declare a Boolean 2-D array and fill it diagonally.
  • Now, check for every possible length, i.e. 0, 1, 2, and so on.
  • If gap=0, that means there is only one element and we put  true since  a single character is palindrome
  • if gap = 1, we check whether extremes are same and if so we put true, else false;
  • Else for any other value of gap, we check if extremes are same and dp[i+1][j-1] yields true, if so then we put true, else false.
  • Each time when a true is encountered, add the string in the set data structure.
  • At last, store all the strings in the set, in an array, and return it.
C++
#include <bits/stdc++.h> using namespace std;  // Function to find all distinct palindrome  // substrings in a given string vector<string> palindromicSubstr(string &str) {     int n = str.length();      // Create a 2D array     vector<vector<bool>> dp(n, vector<bool>(n, false));      // Create a set to store the result     unordered_set<string> result;      // Traverse the string     for (int gap = 0; gap < n; gap++) {         for (int i = 0, j = gap; j < n; i++, j++) {              // If the gap is 0, it is a palindrome             if (gap == 0)                 dp[i][j] = true;              // If the gap is 1, check if              // the characters are the same             else if (gap == 1)                 dp[i][j] = (str[i] == str[j]);              // check if the characters are the same             // and the inner substring is a palindrome             else                 dp[i][j] = (str[i] == str[j] && dp[i + 1][j - 1]);              // If the substring is a palindrome             // insert it into the set             if (dp[i][j])                 result.insert(str.substr(i, j - i + 1));         }     }      // Convert the set to a vector     vector<string> res(result.begin(), result.end());      return res; }  int main() {     string str = "abaaa";     vector<string> result = palindromicSubstr(str);     for(string s : result)         cout << s << " ";     return 0; } 
Java
// Function to find all distinct palindrome  // substrings in a given string import java.util.*;  class GfG {      // Function to find all distinct palindrome      // substrings in a given string     static ArrayList<String> palindromicSubstr(String str) {         int n = str.length();                  // Create a 2D array         boolean[][] dp = new boolean[n][n];                  // Create a set to store the result         HashSet<String> result = new HashSet<>();                  // Traverse the string         for (int gap = 0; gap < n; gap++) {             for (int i = 0, j = gap; j < n; i++, j++) {                                  // If the gap is 0, it is a palindrome                 if (gap == 0)                     dp[i][j] = true;                                  // If the gap is 1, check if                  // the characters are the same                 else if (gap == 1)                     dp[i][j] = (str.charAt(i) == str.charAt(j));                                  // check if the characters are the same                 // and the inner substring is a palindrome                 else                     dp[i][j] = (str.charAt(i) == str.charAt(j)                     && dp[i + 1][j - 1]);                                  // If the substring is a palindrome                 // insert it into the set                 if (dp[i][j])                     result.add(str.substring(i, j + 1));             }         }                  // Convert the set to a vector         ArrayList<String> res = new ArrayList<>(result);                  return res;     }          public static void main(String[] args) {         String str = "abaaa";         ArrayList<String> result = palindromicSubstr(str);         for (String s : result)             System.out.print(s + " ");     } } 
Python
# Function to find all distinct palindrome  # substrings in a given string. def palindromicSubstr(str):     n = len(str)          # Create a 2D array     dp = [[False for _ in range(n)] for _ in range(n)]          # Create a set to store the result     result = set()          # Traverse the string     for gap in range(n):         for i in range(0, n - gap):             j = i + gap                          # If the gap is 0, it is a palindrome             if gap == 0:                 dp[i][j] = True                          # If the gap is 1, check if              # the characters are the same             elif gap == 1:                 dp[i][j] = (str[i] == str[j])                          # check if the characters are the same             # and the inner substring is a palindrome             else:                 dp[i][j] = (str[i] == str[j] and dp[i + 1][j - 1])                          # If the substring is a palindrome             # insert it into the set             if dp[i][j]:                 result.add(str[i:j+1])          # Convert the set to a vector     res = list(result)          return res  if __name__ == "__main__":     str = "abaaa"     result = palindromicSubstr(str)     for s in result:         print(s, end=" ") 
C#
// Function to find all distinct palindrome  // substrings in a given string using System; using System.Collections.Generic;  class GfG {      // Function to find all distinct palindrome      // substrings in a given string     static List<string> PalindromicSubstr(string str) {         int n = str.Length;                  // Create a 2D array         bool[,] dp = new bool[n, n];                  // Create a set to store the result         HashSet<string> result = new HashSet<string>();                  // Traverse the string         for (int gap = 0; gap < n; gap++) {             for (int i = 0, j = gap; j < n; i++, j++) {                                  // If the gap is 0, it is a palindrome                 if (gap == 0)                     dp[i, j] = true;                                  // If the gap is 1, check if                  // the characters are the same                 else if (gap == 1)                     dp[i, j] = (str[i] == str[j]);                                  // check if the characters are the same                 // and the inner substring is a palindrome                 else                     dp[i, j] = (str[i] == str[j]                     && dp[i + 1, j - 1]);                                  // If the substring is a palindrome                 // insert it into the set                 if (dp[i, j])                     result.Add(str.Substring(i, j - i + 1));             }         }                  // Convert the set to a list         List<string> res = new List<string>(result);                  return res;     }          public static void Main(string[] args) {         string str = "abaaa";         List<string> result = PalindromicSubstr(str);         foreach (string s in result)             Console.Write(s + " ");     } } 
JavaScript
// Function to find all distinct palindrome  // substrings in a given string. function palindromicSubstr(str) {     let n = str.length;          // Create a 2D array     let dp = new Array(n);     for (let i = 0; i < n; i++) {         dp[i] = new Array(n).fill(false);     }          // Create a set to store the result     let result = new Set();          // Traverse the string     for (let gap = 0; gap < n; gap++) {         for (let i = 0, j = gap; j < n; i++, j++) {                          // If the gap is 0, it is a palindrome             if (gap === 0)                 dp[i][j] = true;                          // If the gap is 1, check if              // the characters are the same             else if (gap === 1)                 dp[i][j] = (str[i] === str[j]);                          // check if the characters are the same             // and the inner substring is a palindrome             else                 dp[i][j] = (str[i] === str[j] && dp[i + 1][j - 1]);                          // If the substring is a palindrome             // insert it into the set             if (dp[i][j])                 result.add(str.substring(i, j + 1));         }     }          // Convert the set to a vector     let res = Array.from(result);          return res; }   let str = "abaaa"; let result = palindromicSubstr(str); console.log(result.join(" ")); 

Output
a b aa aaa aba 

[Better Approach] – Using Manacher’s Algorithm and Hash Set – O(n ^ 2) Time and O(n ^ 2) Space

The idea is to use Manacher’s Algorithm to find all palindromic substrings and set to store all the distinct one.

Follow the below given steps:

  • Consider each character as a pivot and expand on both sides to find the longest odd-length and even-length palindromes centered at that character; store these lengths in two separate arrays.
  • For every pivot, generate the actual palindromic substrings using the computed lengths.
  • Insert each found palindrome, along with all single characters, into a set so that only distinct palindromic substrings are kept.
  • Finally, store all the palindromes stored in the set in an array and return it.
C++
#include <bits/stdc++.h> using namespace std;  // Function to find all distinct palindrome  // substrings in a given string vector<string> palindromicSubstr(string &str) {     int n = str.length();      // Create a set to store the result     unordered_set<string> result;        // table for storing results of      // odd even length subarrays     vector<vector<int>> dp(2, vector<int>(n + 1, 0));      // store all the palindromic substrings     // of length 1 in the set     for (int i = 0; i < n; i++)         result.insert(str.substr(i, 1));      // insert 'guards' to iterate easily over str     str = "@" + str + "#";      for (int j = 0; j <= 1; j++) {          // length of 'palindrome radius'          int rp = 0;           dp[j][0] = 0;          int i = 1;         while (i <= n) {              // expand palindrome centered at i              while (str[i - rp - 1] == str[i + j + rp])                 rp++;              // Assign the found palindromic length              // to odd/even length array              dp[j][i] = rp;              int k = 1;             while ((dp[j][i - k] != rp - k) && (k < rp)) {                 dp[j][i + k] = min(dp[j][i - k], rp - k);                 k++;             }              // reset the length of palindromic radius             rp = max(rp - k, 0);             i += k;         }     }        // remove 'guards'      str = str.substr(1, n);       // store the results in a set     for (int i = 1; i <= n; i++) {         for (int j = 0; j <= 1; j++) {             for (int rp = dp[j][i]; rp > 0; rp--) {                 result.insert(str.substr(i - rp - 1, 2 * rp + j));             }         }     }          // Convert the set to a vector     vector<string> res(result.begin(), result.end());     return res; }     int main() {     string str = "abaaa";     vector<string> result = palindromicSubstr(str);     for(string str : result)         cout << str << " ";     return 0; } 
Java
// Function to find all distinct palindrome  // substrings in a given string import java.util.*;  class GfG {      // Function to find all distinct palindrome      // substrings in a given string     static ArrayList<String> palindromicSubstr(String str) {         int n = str.length();                  // Create a set to store the result         HashSet<String> result = new HashSet<>();                // table for storing results of          // odd even length subarrays         int[][] dp = new int[2][n + 1];                  // store all the palindromic substrings         // of length 1 in the set         for (int i = 0; i < n; i++)             result.add(str.substring(i, i + 1));                  // insert 'guards' to iterate easily over str         str = "@" + str + "#";                  for (int j = 0; j <= 1; j++) {                          // length of 'palindrome radius'              int rp = 0;               dp[j][0] = 0;                          int i = 1;             while (i <= n) {                                  // expand palindrome centered at i                  while (str.charAt(i - rp - 1) == str.charAt(i + j + rp))                     rp++;                                  // Assign the found palindromic length                  // to odd/even length array                  dp[j][i] = rp;                                  int k = 1;                 while ((dp[j][i - k] != rp - k) && (k < rp)) {                     dp[j][i + k] = Math.min(dp[j][i - k], rp - k);                     k++;                 }                                  // reset the length of palindromic radius                 rp = Math.max(rp - k, 0);                 i += k;             }         }                // remove 'guards'          str = str.substring(1, n + 1);                  // store the results in a set         for (int i = 1; i <= n; i++) {             for (int j = 0; j <= 1; j++) {                 for (int rp = dp[j][i]; rp > 0; rp--) {                     result.add(str.substring(i - rp - 1,                      i - rp - 1 + 2 * rp + j));                 }             }         }                  // Convert the set to a vector         ArrayList<String> res = new ArrayList<>(result);         return res;     }          public static void main(String[] args) {         String str = "abaaa";         ArrayList<String> result = palindromicSubstr(str);         for (String s : result)             System.out.print(s + " ");     } } 
Python
# Function to find all distinct palindrome  # substrings in a given string. def palindromicSubstr(str):     n = len(str)          # Create a set to store the result     result = set()        # table for storing results of      # odd even length subarrays     dp = [[0]*(n+1) for _ in range(2)]          # store all the palindromic substrings     # of length 1 in the set     for i in range(n):         result.add(str[i:i+1])          # insert 'guards' to iterate easily over str     str = "@" + str + "#"          for j in range(2):                  # length of 'palindrome radius'          rp = 0         dp[j][0] = 0                  i = 1         while i <= n:                          # expand palindrome centered at i              while str[i - rp - 1] == str[i + j + rp]:                 rp += 1                          # Assign the found palindromic length              # to odd/even length array              dp[j][i] = rp                          k = 1             while (dp[j][i - k] != rp - k) and (k < rp):                 dp[j][i + k] = min(dp[j][i - k], rp - k)                 k += 1                          # reset the length of palindromic radius             rp = max(rp - k, 0)             i += k          # remove 'guards'      str = str[1:n+1]          # store the results in a set     for i in range(1, n+1):         for j in range(2):             for rp in range(dp[j][i], 0, -1):                 result.add(str[i - rp - 1: i - rp - 1 + 2 * rp + j])          # Convert the set to a vector     res = list(result)     return res  if __name__ == "__main__":     str = "abaaa"     result = palindromicSubstr(str)     for s in result:         print(s, end=" ") 
C#
// Function to find all distinct palindrome  // substrings in a given string using System; using System.Collections.Generic;  class GfG {      // Function to find all distinct palindrome      // substrings in a given string     static List<string> PalindromicSubstr(string str) {         int n = str.Length;                  // Create a set to store the result         HashSet<string> result = new HashSet<string>();                // table for storing results of          // odd even length subarrays         int[,] dp = new int[2, n + 1];                  // store all the palindromic substrings         // of length 1 in the set         for (int i = 0; i < n; i++)             result.Add(str.Substring(i, 1));                  // insert 'guards' to iterate easily over str         str = "@" + str + "#";                  for (int j = 0; j <= 1; j++) {                          // length of 'palindrome radius'              int rp = 0;               dp[j, 0] = 0;                          int i = 1;             while (i <= n) {                                  // expand palindrome centered at i                  while (str[i - rp - 1] == str[i + j + rp])                     rp++;                                  // Assign the found palindromic length                  // to odd/even length array                  dp[j, i] = rp;                                  int k = 1;                 while ((dp[j, i - k] != rp - k) && (k < rp)) {                     dp[j, i + k] = Math.Min(dp[j, i - k], rp - k);                     k++;                 }                                  // reset the length of palindromic radius                 rp = Math.Max(rp - k, 0);                 i += k;             }         }                // remove 'guards'          str = str.Substring(1, n);                  // store the results in a set         for (int i = 1; i <= n; i++) {             for (int j = 0; j <= 1; j++) {                 for (int rp = dp[j, i]; rp > 0; rp--) {                     result.Add(str.Substring(i - rp - 1, 2 * rp + j));                 }             }         }                  // Convert the set to a list         List<string> res = new List<string>(result);         return res;     }          public static void Main(string[] args) {         string str = "abaaa";         List<string> result = PalindromicSubstr(str);         foreach (string s in result)             Console.Write(s + " ");     } } 
JavaScript
// Function to find all distinct palindrome  // substrings in a given string. function palindromicSubstr(str) {     let n = str.length;          // Create a set to store the result     let result = new Set();        // table for storing results of      // odd even length subarrays     let dp = [new Array(n + 1).fill(0), new Array(n + 1).fill(0)];          // store all the palindromic substrings     // of length 1 in the set     for (let i = 0; i < n; i++)         result.add(str.substring(i, i + 1));          // insert 'guards' to iterate easily over str     str = "@" + str + "#";          for (let j = 0; j <= 1; j++) {                  // length of 'palindrome radius'          let rp = 0;         dp[j][0] = 0;                  let i = 1;         while (i <= n) {                          // expand palindrome centered at i              while (str[i - rp - 1] === str[i + j + rp])                 rp++;                          // Assign the found palindromic length              // to odd/even length array              dp[j][i] = rp;                          let k = 1;             while ((dp[j][i - k] !== rp - k) && (k < rp)) {                 dp[j][i + k] = Math.min(dp[j][i - k], rp - k);                 k++;             }                          // reset the length of palindromic radius             rp = Math.max(rp - k, 0);             i += k;         }     }        // remove 'guards'      str = str.substring(1, n + 1);          // store the results in a set     for (let i = 1; i <= n; i++) {         for (let j = 0; j <= 1; j++) {             for (let rp = dp[j][i]; rp > 0; rp--) {                 result.add(str.substring(i - rp - 1,                  i - rp - 1 + 2 * rp + j));             }         }     }          // Convert the set to a vector     let res = Array.from(result);     return res; }   let str = "abaaa"; let result = palindromicSubstr(str); console.log(result.join(" ")); 

Output
a b aaa aba aa 

[Expected Approach] – Using Dynamic Programming and KMP Algorithm – O(n^2) Time and O(n^2) Space

The idea is to identify all palindromic substrings in a given string using a dynamic programming method, then eliminate duplicates by leveraging the KMP algorithm, and finally print the distinct palindromes along with their count.

Follow the below given steps:

  • First, for every possible substring, use dynamic programming to check if it is a palindrome.
  • Next, for every index starting from 0, apply the KMP algorithm to compare prefixes and suffixes. If a substring is both a palindrome and its prefix matches its suffix, mark it (for example, by setting the corresponding dp value to false) so that duplicate occurrences are removed.
  • Finally, iterate over all substrings and print those that remain marked as palindromic in the dp array; the number of such entries gives the total count of distinct palindromic substrings.
C++
#include <bits/stdc++.h> using namespace std;  // Function to find all distinct palindrome  // substrings in a given string vector<string> palindromicSubstr(string &str) {     int n = str.length();      // Create a 2D array     vector<vector<bool>> dp(n, vector<bool>(n, false));      for (int i = 0; i < n; i++) {          // base case every char is palindrome         dp[i][i] = 1;          // check for every substring of length 2         if (i < n && str[i] == str[i + 1]) {             dp[i][i + 1] = 1;         }     }      // check every substring of length      // greater than 2 for palindrome     for (int len = 3; len <= n; len++) {         for (int i = 0; i + len - 1 < n; i++) {             if (str[i] == str[i + (len - 1)]                 && dp[i + 1][i + (len - 1) - 1]) {                 dp[i][i + (len - 1)] = true;             }         }     }      // create an array of size n     // to operate the kmp algorithm     vector<int> kmp(n, 0);      for (int i = 0; i < n; i++) {          // starting kmp for every i from 0 to n-1         int j = 0, k = 1;          while (k + i < n) {             if (str[j + i] == str[k + i]) {                  // make suffix to be false, if this suffix is                  // palindrome then it is included in prefix                 dp[k + i - j][k + i] = false;                 kmp[k++] = ++j;             }             else if (j > 0) {                 j = kmp[j - 1];             }             else {                 kmp[k++] = 0;             }         }     }          // Create an array to store the result     vector<string> result;      for (int i = 0; i < n; i++) {          // to store the current string         string cur;         for (int j = i; j < n; j++) {             cur += str[j];             if (dp[i][j]) {                 result.push_back(cur);             }         }     }     return result; }  int main() {     string str = "abaaa";     vector<string> result = palindromicSubstr(str);     for(string s : result)         cout << s << " ";     return 0; } 
Java
// Function to find all distinct palindrome  // substrings in a given string import java.util.*;  class GfG {      // Function to find all distinct palindrome      // substrings in a given string     static ArrayList<String> palindromicSubstr(String str) {         int n = str.length();                  // Create a 2D array         boolean[][] dp = new boolean[n][n];                  for (int i = 0; i < n; i++) {                          // base case every char is palindrome             dp[i][i] = true;                          // check for every substring of length 2             if (i < n - 1 && str.charAt(i) == str.charAt(i + 1)) {                 dp[i][i + 1] = true;             }         }                  // check every substring of length          // greater than 2 for palindrome         for (int len = 3; len <= n; len++) {             for (int i = 0; i + len - 1 < n; i++) {                 if (str.charAt(i) == str.charAt(i + len - 1)                  && dp[i + 1][i + len - 2]) {                     dp[i][i + len - 1] = true;                 }             }         }                  // create an array of size n         // to operate the kmp algorithm         int[] kmp = new int[n];         Arrays.fill(kmp, 0);                  for (int i = 0; i < n; i++) {                          // starting kmp for every i from 0 to n-1             int j = 0, k = 1;             while (k + i < n) {                 if (str.charAt(j + i) == str.charAt(k + i)) {                                          // make suffix to be false, if this suffix is                      // palindrome then it is included in prefix                     dp[k + i - j][k + i] = false;                     kmp[k++] = ++j;                 }                 else if (j > 0) {                     j = kmp[j - 1];                 }                 else {                     kmp[k++] = 0;                 }             }         }                  // Create an array to store the result         ArrayList<String> result = new ArrayList<>();                  for (int i = 0; i < n; i++) {                          // to store the current string             String cur = "";             for (int j = i; j < n; j++) {                 cur += str.charAt(j);                 if (dp[i][j]) {                     result.add(cur);                 }             }         }         return result;     }          public static void main(String[] args) {         String str = "abaaa";         ArrayList<String> result = palindromicSubstr(str);         for (String s : result)             System.out.print(s + " ");     } } 
Python
# Function to find all distinct palindrome  # substrings in a given string. def palindromicSubstr(str):     n = len(str)          # Create a 2D array     dp = [[False for _ in range(n)] for _ in range(n)]          for i in range(n):         # base case every char is palindrome         dp[i][i] = True                  # check for every substring of length 2         if i < n - 1 and str[i] == str[i + 1]:             dp[i][i + 1] = True          # check every substring of length      # greater than 2 for palindrome     for length in range(3, n + 1):         for i in range(n - length + 1):             j = i + length - 1             if str[i] == str[j] and dp[i + 1][j - 1]:                 dp[i][j] = True          # create an array of size n     # to operate the kmp algorithm     kmp = [0] * n          for i in range(n):         # starting kmp for every i from 0 to n-1         j = 0         k = 1         while k + i < n:             if str[i + j] == str[i + k]:                 # make suffix to be false, if this suffix is                  # palindrome then it is included in prefix                 dp[i + k - j][i + k] = False                 kmp[k] = j + 1                 j += 1                 k += 1             elif j > 0:                 j = kmp[j - 1]             else:                 kmp[k] = 0                 k += 1          # Create an array to store the result     result = []          for i in range(n):         # to store the current string         cur = ""         for j in range(i, n):             cur += str[j]             if dp[i][j]:                 result.append(cur)     return result  if __name__ == "__main__":     str = "abaaa"     result = palindromicSubstr(str)     for s in result:         print(s, end=" ") 
C#
// Function to find all distinct palindrome  // substrings in a given string using System; using System.Collections.Generic;  class GfG {      // Function to find all distinct palindrome      // substrings in a given string.     static List<string> palindromicSubstr(ref string str) {         int n = str.Length;                  // Create a 2D array         bool[,] dp = new bool[n, n];         for (int i = 0; i < n; i++) {             // base case every char is palindrome             dp[i, i] = true;                          // check for every substring of length 2             if (i < n - 1 && str[i] == str[i + 1])                 dp[i, i + 1] = true;         }                  // check every substring of length          // greater than 2 for palindrome         for (int len = 3; len <= n; len++) {             for (int i = 0; i + len - 1 < n; i++) {                 int j = i + len - 1;                 if (str[i] == str[j] && dp[i + 1, j - 1])                     dp[i, j] = true;             }         }                  // create an array of size n         // to operate the kmp algorithm         int[] kmp = new int[n];         for (int i = 0; i < n; i++) {             kmp[i] = 0;         }                  for (int i = 0; i < n; i++) {             // starting kmp for every i from 0 to n-1             int j = 0, k = 1;             while (k + i < n) {                 if (str[i + j] == str[i + k]) {                     // make suffix to be false, if this suffix is                      // palindrome then it is included in prefix                     dp[i + k - j, i + k] = false;                     kmp[k] = ++j;                     k++;                 }                 else if (j > 0) {                     j = kmp[j - 1];                 }                 else {                     kmp[k] = 0;                     k++;                 }             }         }                  // Create an array to store the result         List<string> result = new List<string>();                  for (int i = 0; i < n; i++) {             // to store the current string             string cur = "";             for (int j = i; j < n; j++) {                 cur += str[j];                 if (dp[i, j])                     result.Add(cur);             }         }         return result;     }          static void Main() {         string str = "abaaa";         List<string> result = palindromicSubstr(ref str);         foreach (string s in result)             Console.Write(s + " ");     } } 
JavaScript
// Function to find all distinct palindrome  // substrings in a given string. function palindromicSubstr(str) {     let n = str.length;          // Create a 2D array     let dp = new Array(n);     for (let i = 0; i < n; i++) {         dp[i] = new Array(n).fill(false);     }          for (let i = 0; i < n; i++) {         // base case every char is palindrome         dp[i][i] = true;                  // check for every substring of length 2         if (i < n - 1 && str[i] === str[i + 1])             dp[i][i + 1] = true;     }          // check every substring of length      // greater than 2 for palindrome     for (let len = 3; len <= n; len++) {         for (let i = 0; i + len - 1 < n; i++) {             let j = i + len - 1;             if (str[i] === str[j] && dp[i + 1][j - 1])                 dp[i][j] = true;         }     }          // create an array of size n     // to operate the kmp algorithm     let kmp = new Array(n).fill(0);          for (let i = 0; i < n; i++) {         // starting kmp for every i from 0 to n-1         let j = 0, k = 1;         while (k + i < n) {             if (str[i + j] === str[i + k]) {                 // make suffix to be false, if this suffix is                  // palindrome then it is included in prefix                 dp[i + k - j][i + k] = false;                 kmp[k] = ++j;                 k++;             } else if (j > 0) {                 j = kmp[j - 1];             } else {                 kmp[k] = 0;                 k++;             }         }     }          // Create an array to store the result     let result = [];          for (let i = 0; i < n; i++) {         // to store the current string         let cur = "";         for (let j = i; j < n; j++) {             cur += str[j];             if (dp[i][j])                 result.push(cur);         }     }     return result; }   let str = "abaaa"; let result = palindromicSubstr(str); console.log(result.join(" ")); 

Output
a aba b aa aaa 

[Alternate Approach] – Using Center Expansion and Set – O(n ^ 2) Time and O(n ^ 2) Space

The idea is to use center expansion technique to find all even and odd length palindromic substrings separately, and then store them in a set to find the unique palindromic substrings.

C++
#include <bits/stdc++.h> using namespace std;  // Function to find all distinct palindrome  // substrings in a given string vector<string> palindromicSubstr(string &str) {     int n = str.length();      // Create a set to store the result     unordered_set<string> result;      // Check for odd length palindromes     for (int i = 0; i < n; i++) {         int left = i, right = i;         while (left >= 0 && right < n && str[left] == str[right]) {              // Add the palindrome substring             result.insert(str.substr(left, right - left + 1));             left--, right++;         }     }      // Check for even length palindromes     for (int i = 0; i < n - 1; i++) {         int left = i, right = i + 1;         while (left >= 0 && right < n && str[left] == str[right]) {              // Add the palindrome substring             result.insert(str.substr(left, right - left + 1));             left--, right++;         }     }      // Convert the set to a vector     vector<string> res(result.begin(), result.end());      return res; }  int main() {     string str = "abaaa";     vector<string> result = palindromicSubstr(str);     for(string str : result)         cout << str << " ";     return 0; } 
Java
// Function to find all distinct palindrome  // substrings in a given string import java.util.*;  class GfG {      // Function to find all distinct palindrome      // substrings in a given string     static ArrayList<String> palindromicSubstr(String str) {         int n = str.length();                  // Create a set to store the result         HashSet<String> result = new HashSet<>();                  // Check for odd length palindromes         for (int i = 0; i < n; i++) {             int left = i, right = i;             while (left >= 0 && right < n &&              str.charAt(left) == str.charAt(right)) {                                  // Add the palindrome substring                 result.add(str.substring(left, right + 1));                 left--;                 right++;             }         }                  // Check for even length palindromes         for (int i = 0; i < n - 1; i++) {             int left = i, right = i + 1;             while (left >= 0 && right < n && str.charAt(left) == str.charAt(right)) {                                  // Add the palindrome substring                 result.add(str.substring(left, right + 1));                 left--;                 right++;             }         }                  // Convert the set to a vector         ArrayList<String> res = new ArrayList<>(result);                  return res;     }          public static void main(String[] args) {         String str = "abaaa";         ArrayList<String> result = palindromicSubstr(str);         for (String s : result)             System.out.print(s + " ");     } } 
Python
from __future__ import print_function  # Function to find all distinct palindrome  # substrings in a given string. def palindromicSubstr(str):     n = len(str)          # Create a set to store the result     result = set()          # Check for odd length palindromes     for i in range(n):         left = i         right = i         while left >= 0 and right < n and str[left] == str[right]:                          # Add the palindrome substring             result.add(str[left:right+1])             left -= 1             right += 1          # Check for even length palindromes     for i in range(n - 1):         left = i         right = i + 1         while left >= 0 and right < n and str[left] == str[right]:                          # Add the palindrome substring             result.add(str[left:right+1])             left -= 1             right += 1          # Convert the set to a vector     res = list(result)     return res  if __name__ == "__main__":     str = "abaaa"     result = palindromicSubstr(str)     for s in result:         print(s, end=" ") 
C#
// Function to find all distinct palindrome  // substrings in a given string using System; using System.Collections.Generic; using System.Linq;  class GfG {      // Function to find all distinct palindrome      // substrings in a given string     static List<string> PalindromicSubstr(string str) {         int n = str.Length;                  // Create a set to store the result         HashSet<string> result = new HashSet<string>();                  // Check for odd length palindromes         for (int i = 0; i < n; i++) {             int left = i, right = i;             while (left >= 0 && right < n &&              str[left] == str[right]) {                                  // Add the palindrome substring                 result.Add(str.Substring(left, right - left + 1));                 left--;                 right++;             }         }                  // Check for even length palindromes         for (int i = 0; i < n - 1; i++) {             int left = i, right = i + 1;             while (left >= 0 && right < n && str[left] == str[right]) {                                  // Add the palindrome substring                 result.Add(str.Substring(left, right - left + 1));                 left--;                 right++;             }         }                  // Convert the set to a list         List<string> res = result.ToList();                  return res;     }          public static void Main(string[] args) {         string str = "abaaa";         List<string> result = PalindromicSubstr(str);         foreach (string s in result)             Console.Write(s + " ");     } } 
JavaScript
// Function to find all distinct palindrome  // substrings in a given string. function palindromicSubstr(str) {     let n = str.length;          // Create a set to store the result     let result = new Set();          // Check for odd length palindromes     for (let i = 0; i < n; i++) {         let left = i, right = i;         while (left >= 0 && right < n && str[left] === str[right]) {                          // Add the palindrome substring             result.add(str.substring(left, right + 1));             left--;             right++;         }     }          // Check for even length palindromes     for (let i = 0; i < n - 1; i++) {         let left = i, right = i + 1;         while (left >= 0 && right < n && str[left] === str[right]) {                          // Add the palindrome substring             result.add(str.substring(left, right + 1));             left--;             right++;         }     }          // Convert the set to a vector     let res = Array.from(result);     return res; }   let str = "abaaa"; let result = palindromicSubstr(str); console.log(result.join(" ")); 

Output
aa a b aba aaa 

Related Article: 
Count All Palindrome Sub-Strings in a String



Next Article
Find all Palindrome Strings in given Array of strings

V

Vignesh Narayanan and Sowmya Sampath
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • Strings
  • Linkedin
  • MakeMyTrip
  • Ola Cabs
  • palindrome
  • SAP Labs
  • STL
Practice Tags :
  • Linkedin
  • MakeMyTrip
  • Ola Cabs
  • SAP Labs
  • Dynamic Programming
  • palindrome
  • STL
  • Strings

Similar Reads

  • Find all Palindrome Strings in given Array of strings
    Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array. Examples: Input: arr[] = {"abc", "car", "ada", "racecar", "cool"}Output: "ada", "ra
    6 min read
  • Distinct palindromic sub-strings of the given string using Dynamic Programming
    Given a string str of lowercase alphabets, the task is to find all distinct palindromic sub-strings of the given string. Examples: Input: str = "abaaa" Output: 5 Palindromic sub-strings are "a", "aa", "aaa", "aba" and "b" Input: str = "abcd" Output: 4 Approach: The solution to this problem has been
    8 min read
  • Generate a String of having N*N distinct non-palindromic Substrings
    Given an even integer N, the task is to construct a string such that the total number of distinct substrings of that string that are not a palindrome equals N2. Examples: Input: N = 2 Output: aabb Explanation: All the distinct non-palindromic substrings are ab, abb, aab and aabb. Therefore, the coun
    4 min read
  • Check if a string contains a palindromic sub-string of even length
    S is string containing only lowercase English alphabets. We need to find if there exists at least one palindromic sub-string whose length is even. Examples: Input : aassssOutput : YESInput : gfgOutput : NOApproach: Approach to solve this problem is to check all even-length substrings of the given st
    8 min read
  • Count substrings of a given string whose anagram is a palindrome
    Given a string S of length N containing only lowercase alphabets, the task is to print the count of substrings of the given string whose anagram is palindromic. Examples: Input: S = "aaaa"Output: 10Explanation:Possible substrings are {"a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"}. Sinc
    10 min read
  • Count of Palindrome Strings in given Array of strings
    Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to return the count of all palindromic string in the array. Examples: Input: arr[] = {"abc","car","ada","racecar","cool"}Output: 2Explanation: "ada" and "racecar" are the two palindrome
    5 min read
  • Count All Palindromic Subsequence in a given String
    Given a string s of length n, the task is to count number of palindromic subsequence (need not necessarily be distinct) present in the string s. Example: Input: s = "abcd"Output: 4Explanation: Palindromic subsequence are : "a" ,"b", "c" ,"d" Input: s = "aab"Output: 4Explanation: palindromic subseque
    15+ min read
  • Make a palindromic string from given string
    Given a string S consisting of lower-case English alphabets only, we have two players playing the game. The rules are as follows: The player can remove any character from the given string S and write it on paper on any side(left or right) of an empty string.The player wins the game, if at any move h
    7 min read
  • Count Palindromic Substrings in a Binary String
    Given a binary string S i.e. which consists only of 0's and 1's. Calculate the number of substrings of S which are palindromes. String S contains at most two 1's. Examples: Input: S = "011"Output: 4Explanation: "0", "1", "1" and "11" are the palindromic substrings. Input: S = "0" Output: 1Explanatio
    7 min read
  • Count all palindromic Substrings for each character in a given String
    Given a string S of length n, for each character S[i], the task is to find the number of palindromic substrings of length K such that no substring should contain S[i], the task is to return an array A of length n, where A[i] is the count of palindromic substrings of length K which does not include t
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences