Distinct palindromic sub-strings of the given string using Dynamic Programming
Last Updated :
13 Jul, 2023
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>
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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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