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
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Rearrange the string to maximize the number of palindromic substrings
Next article icon

Distinct palindromic sub-strings of the given string using Dynamic Programming

Last Updated : 13 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 discussed here using Manacher’s algorithm. However we can also solve it using dynamic programming. 
Create an array dp[][] where dp[i][j] is set to 1 if str[i…j] is a palindrome else 0. After the array has been generated, store all the palindromic sub-strings in a map in order to get the count of distinct sub-strings.

Below is the implementation of the above approach:  

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the count
// of distinct palindromic sub-strings
// of the given string s
int palindromeSubStrs(string s)
{
 
    // To store the positions of
    // palindromic sub-strings
    int dp[s.size()][s.size()];
    int st, end, i, j, len;
 
    // Map to store the sub-strings
    map<string, bool> m;
    for (i = 0; i < s.size(); i++) {
 
        // Sub-strings of length 1 are palindromes
        dp[i][i] = 1;
 
        // Store continuous palindromic sub-strings
        m[string(s.begin() + i, s.begin() + i + 1)] = 1;
    }
 
    // Store palindromes of size 2
    for (i = 0; i < s.size() - 1; i++) {
        if (s[i] == s[i + 1]) {
            dp[i][i + 1] = 1;
            m[string(s.begin() + i, s.begin() + i + 2)] = 1;
        }
 
        // If str[i...(i+1)] is not a palindromic
        // then set dp[i][i + 1] = 0
        else {
            dp[i][i + 1] = 0;
        }
    }
 
    // Find palindromic sub-strings of length>=3
    for (len = 3; len <= s.size(); len++) {
        for (st = 0; st <= s.size() - len; st++) {
 
            // End of palindromic substring
            end = st + len - 1;
 
            // If s[start] == s[end] and
            // dp[start+1][end-1] is already palindrome
            // then s[start....end] is also a palindrome
            if (s[st] == s[end] && dp[st + 1][end - 1]) {
 
                // Set dp[start][end] = 1
                dp[st][end] = 1;
                m[string(s.begin() + st, s.begin() + end + 1)] = 1;
            }
 
            // Not a palindrome
            else
                dp[st][end] = 0;
        }
    }
 
    // Return the count of distinct palindromes
    return m.size();
}
 
// Driver code
int main()
{
    string s = "abaaa";
    cout << palindromeSubStrs(s);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.util.HashMap;
 
class GFG
{
 
    // Function to return the count
    // of distinct palindromic sub-strings
    // of the given string s
    static int palindromeSubStrs(String s)
    {
 
        // To store the positions of
        // palindromic sub-strings
        int[][] dp = new int[s.length()][s.length()];
        int st, end, i, len;
 
        // Map to store the sub-strings
        HashMap<String,
                Boolean> m = new HashMap<>();
 
        for (i = 0; i < s.length(); i++)
        {
 
            // Sub-strings of length 1 are palindromes
            dp[i][i] = 1;
 
            // Store continuous palindromic sub-strings
            m.put(s.substring(i, i + 1), true);
        }
 
        // Store palindromes of size 2
        for (i = 0; i < s.length() - 1; i++)
        {
            if (s.charAt(i) == s.charAt(i + 1))
            {
                dp[i][i + 1] = 1;
                m.put(s.substring(i, i + 2), true);
            }
 
            // If str[i...(i+1)] is not a palindromic
            // then set dp[i][i + 1] = 0
            else
                dp[i][i + 1] = 0;
        }
 
        // Find palindromic sub-strings of length>=3
        for (len = 3; len <= s.length(); len++)
        {
            for (st = 0; st <= s.length() - len; st++)
            {
 
                // End of palindromic substring
                end = st + len - 1;
 
                // If s[start] == s[end] and
                // dp[start+1][end-1] is already palindrome
                // then s[start....end] is also a palindrome
                if (s.charAt(st) == s.charAt(end) &&
                    dp[st + 1][end - 1] == 1)
                {
 
                    // Set dp[start][end] = 1
                    dp[st][end] = 1;
                    m.put(s.substring(st, end + 1), true);
                }
 
                // Not a palindrome
                else
                    dp[st][end] = 0;
            }
        }
 
        // Return the count of distinct palindromes
        return m.size();
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String s = "abaaa";
        System.out.println(palindromeSubStrs(s));
    }
}
 
// This code is contributed by
// sanjeev2552
 
 

Python3




# Python3 implementation of the approach
 
# import numpy lib as np
import numpy as np;
 
# Function to return the count
# of distinct palindromic sub-strings
# of the given string s
def palindromeSubStrs(s) :
 
    # To store the positions of
    # palindromic sub-strings
    dp = np.zeros((len(s),len(s)));
     
    # Map to store the sub-strings
    m = {};
     
    for i in range(len(s)) :
 
        # Sub-strings of length 1 are palindromes
        dp[i][i] = 1;
 
        # Store continuous palindromic sub-strings
        m[s[i: i + 1]] = 1;
     
 
    # Store palindromes of size 2
    for i in range(len(s)- 1) :
        if (s[i] == s[i + 1]) :
            dp[i][i + 1] = 1;
            m[ s[i : i + 2]] = 1;
          
 
        # If str[i...(i+1)] is not a palindromic
        # then set dp[i][i + 1] = 0
        else :
            dp[i][i + 1] = 0;
 
    # Find palindromic sub-strings of length>=3
    for length in range(3,len(s) + 1) :
        for st in range(len(s) - length + 1) :
 
            # End of palindromic substring
            end = st + length - 1;
 
            # If s[start] == s[end] and
            # dp[start+1][end-1] is already palindrome
            # then s[start....end] is also a palindrome
            if (s[st] == s[end] and dp[st + 1][end - 1]) :
 
                # Set dp[start][end] = 1
                dp[st][end] = 1;
                m[s[st : end + 1]] = 1;
 
            # Not a palindrome
            else :
                dp[st][end] = 0;
 
    # Return the count of distinct palindromes
    return len(m);
 
 
# Driver code
if __name__ == "__main__" :
 
    s = "abaaa";
    print(palindromeSubStrs(s));
 
# This code is contributed by AnkitRai01
 
 

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to return the count
    // of distinct palindromic sub-strings
    // of the given string s
    static int palindromeSubStrs(String s)
    {
 
        // To store the positions of
        // palindromic sub-strings
        int[,] dp = new int[s.Length, s.Length];
        int st, end, i, len;
 
        // Map to store the sub-strings
        Dictionary<String,
                Boolean> m = new Dictionary<String,
                Boolean>();
 
        for (i = 0; i < s.Length; i++)
        {
 
            // Sub-strings of length 1 are palindromes
            dp[i,i] = 1;
 
            // Store continuous palindromic sub-strings
            if(!m.ContainsKey(s.Substring(i, 1)))
                m.Add(s.Substring(i, 1), true);
        }
 
        // Store palindromes of size 2
        for (i = 0; i < s.Length - 1; i++)
        {
            if (s[i] == s[i + 1])
            {
                dp[i, i + 1] = 1;
                if(!m.ContainsKey(s.Substring(i, 2)))
                    m.Add(s.Substring(i, 2), true);
            }
 
            // If str[i...(i+1)] is not a palindromic
            // then set dp[i,i + 1] = 0
            else
                dp[i, i + 1] = 0;
        }
 
        // Find palindromic sub-strings of length>=3
        for (len = 3; len <= s.Length; len++)
        {
            for (st = 0; st <= s.Length - len; st++)
            {
 
                // End of palindromic substring
                end = st + len - 1;
 
                // If s[start] == s[end] and
                // dp[start+1,end-1] is already palindrome
                // then s[start....end] is also a palindrome
                if (s[st] == s[end] &&
                    dp[st + 1, end - 1] == 1)
                {
 
                    // Set dp[start,end] = 1
                    dp[st, end] = 1;
                    m.Add(s.Substring(st, end + 1-st), true);
                }
 
                // Not a palindrome
                else
                    dp[st, end] = 0;
            }
        }
 
        // Return the count of distinct palindromes
        return m.Count;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        String s = "abaaa";
        Console.WriteLine(palindromeSubStrs(s));
    }
}
 
// This code is contributed by PrinciRaj1992
 
 

Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the count
// of distinct palindromic sub-strings
// of the given string s
function palindromeSubStrs(s)
{
     
    // To store the positions of
    // palindromic sub-strings
    let dp = new Array(s.length);
    for(let i = 0; i < dp.length; i++)
    {
        dp[i] = new Array(2);
    }
             
    for(let i = 0; i < dp.length; i++)
    {
        for(let j = 0; j < dp.length; j++)
        {
            dp[i][j] = 0;
        }
    }
    let st, end, i, len;
 
    // Map to store the sub-strings
    let m = new Map();
 
    for(i = 0; i < s.length; i++)
    {
         
        // Sub-strings of length 1 are palindromes
        dp[i][i] = 1;
 
        // Store continuous palindromic sub-strings
        m.set(s.substr(i, i + 1), true);
    }
 
    // Store palindromes of size 2
    for(i = 0; i < s.length - 1; i++)
    {
        if (s[i] == s[i + 1])
        {
            dp[i][i + 1] = 1;
            m.set(s.substr(i, i + 2), true);
        }
 
        // If str[i...(i+1)] is not a palindromic
        // then set dp[i][i + 1] = 0
        else
            dp[i][i + 1] = 0;
    }
 
    // Find palindromic sub-strings of length>=3
    for(len = 3; len <= s.length; len++)
    {
        for(st = 0; st <= s.length - len; st++)
        {
             
            // End of palindromic substring
            end = st + len - 1;
 
            // If s[start] == s[end] and
            // dp[start+1][end-1] is already palindrome
            // then s[start....end] is also a palindrome
            if (s[st] == s[end] &&
                dp[st + 1][end - 1] == 1)
            {
 
                // Set dp[start][end] = 1
                dp[st][end] = 1;
                m.set(s.substr(st, end + 1), true);
            }
 
            // Not a palindrome
            else
                dp[st][end] = 0;
        }
    }
 
    // Return the count of distinct palindromes
    return m.size;
}
 
// Driver Code
let s = "abaaa";
document.write(palindromeSubStrs(s));
 
// This code is contributed by code_hunt
 
</script>
 
 
Output
5 

Time complexity : O((n^2)logn), where n is the length of the input string. This is because we are using a nested loop to iterate over all possible substrings and check if they are palindromic.

Space complexity : O(n^2). This is because we are using a 2D array of size n x n to store the results of subproblems, and a map to store the distinct palindromic substrings.



Next Article
Rearrange the string to maximize the number of palindromic substrings
author
md1844
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • Strings
  • palindrome
  • substring
Practice Tags :
  • Dynamic Programming
  • palindrome
  • Strings

Similar Reads

  • All distinct palindromic sub-strings of a given string
    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 list
    15+ min read
  • Longest Palindromic Substring using Dynamic Programming
    Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first occurrence of the longest palindromic substring from left to right. Examples: Input: s = "aaaabbaa"Output: "aabbaa"Explanation: The longest palindromic substring is
    7 min read
  • Rearrange the string to maximize the number of palindromic substrings
    Given a string S consisting of lowercase characters(a-z) only, the task is to print a new string by rearranging the string in such a way that maximizes the number of palindromic substrings. In case of multiple answers, print any one. Note: even if some substrings coincide, count them as many times a
    5 min read
  • Palindromic strings of length 3 possible by using characters of a given string
    Given a string S consisting of N characters, the task is to print all palindromic strings of length 3 in lexicographical order that can be formed using characters of the given string S. Examples: Input: S = "aabc"Output:abaaca Input: S = "ddadbac"Output:abaacaadadaddbddcdddd Approach: The given prob
    9 min read
  • Permutation of given string that maximizes count of Palindromic substrings
    Given a string S, the task is to find the permutation of the string such that palindromic substrings in the string are maximum.Note: There can be multiple answers for each string. Examples: Input: S = "abcb" Output: "abbc" Explanation: "abbc" is the string with maximum number of palindromic substrin
    3 min read
  • Largest palindromic string possible from given strings by rearranging the characters
    Given two strings S and P, the task is to find the largest palindrome possible string by choosing characters from the given strings S and P after rearranging the characters. Note: If many answers are possible, then find the lexicographically smallest T with maximum length. Examples: Input: S = "abad
    13 min read
  • Number of strings of length N with no palindromic sub string
    Given two positive integers N, M. The task is to find the number of strings of length N under the alphabet set of size M such that no substrings of size greater than 1 is palindromic. Examples: Input : N = 2, M = 3 Output : 6 In this case, set of alphabet are 3, say {A, B, C} All possible string of
    5 min read
  • Count pairs of non-overlapping palindromic sub-strings of the given string
    Given a string S. The task is to count the non-overlapping pairs of palindromic sub-strings S1 and S2 such that the strings should be S1[L1...R1] and S2[L2...R2] where 0 ? L1 ? R1 < L2 ? R2 < N. The task is to count the number of pairs of the non-overlapping palindromic sub-strings. Examples:
    13 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
  • Split string into three palindromic substrings with earliest possible cuts
    Given string str, the task is to check if it is possible to split the given string S into three palindromic substrings or not. If multiple answers are possible, then print the one where the cuts are made the least indices. If no such possible partition exists, then print "-1". Examples: Input: str =
    15+ 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