Minimum steps to delete a string after repeated deletion of palindrome substrings
Last Updated : 17 Mar, 2025
Given a string str, containing only digits from ‘0’ to ‘9’. Your task is to find the minimum number of operations required to delete all the digits of string, where in each operation we can delete a palindromic substring.
Note: After deleting the substring, the remaining parts are concatenated.
Examples:
Input: str = “2553432”
Output: 2
Explanation: We can first delete the substring “55”, and the remaining string will be “23432”, which is a palindrome and can be deleted in second operation.
Input: str = “1234”
Output: 4
Explanation: All 4 digits need to be deleted separately. Note that a single character is also a palindrome.
[Naive Approach] – Using Recursion – Exponential Time
We can use recursion to solve the problem.
minOps(atr, start, end):
- If the size of the string is one then only one operation is needed.
- Else If the size of the string is 2 and both characters are the same then return 1.
- Else If the size is more than 2 and first two characters are same, then recursively call for minOps(atr, start + 2, end)
- Else Initialize result as minOps(atr, start + 1, end)
- Now search for the starting character ( str[start] ) in the remaining substring. i.e., we search for i = start + 2 to end. If we find a match, i.e., if str[start] = str[end], then make two recursive calls. minOps(str, start + 1, i – 1) and minOps(str, i + 1, end)
C++ #include <bits/stdc++.h> using namespace std; // Recursive function to find the minimum operations // required to delete a string int minOp(string &str, int start, int end) { // if the string is empty if (start > end) return 0; // if the string has only one character if (start == end) return 1; // if string has only two characters and both are same if (start + 1 == end && str[start] == str[end]) return 1; // remove the first character and operate on the rest int res = 1 + minOp(str, start + 1, end); // if the first two characters are same if (str[start] == str[start + 1]) res = min(res, 1 + minOp(str, start + 2, end)); // find the index of the next character same as the first for (int i = start + 2; i <= end; i++) { if (str[start] == str[i]) { res = min(res, minOp(str, start + 1, i - 1) + minOp(str, i + 1, end)); } } return res; } int main() { string str = "2553432"; cout << minOp(str, 0, str.size()-1); return 0; }
Java // Recursive function to find the minimum operations // required to delete a string public class MinOperations { public static int minOp(String str, int start, int end) { // if the string is empty if (start > end) return 0; // if the string has only one character if (start == end) return 1; // if string has only two characters and both are same if (start + 1 == end && str.charAt(start) == str.charAt(end)) return 1; // remove the first character and operate on the rest int res = 1 + minOp(str, start + 1, end); // if the first two characters are same if (str.charAt(start) == str.charAt(start + 1)) res = Math.min(res, 1 + minOp(str, start + 2, end)); // find the index of the next character same as the first for (int i = start + 2; i <= end; i++) { if (str.charAt(start) == str.charAt(i)) { res = Math.min(res, minOp(str, start + 1, i - 1) + minOp(str, i + 1, end)); } } return res; } public static void main(String[] args) { String str = "2553432"; System.out.println(minOp(str, 0, str.length() - 1)); } }
Python # Recursive function to find the minimum operations # required to delete a string def min_op(s, start, end): # if the string is empty if start > end: return 0 # if the string has only one character if start == end: return 1 # if string has only two characters and both are same if start + 1 == end and s[start] == s[end]: return 1 # remove the first character and operate on the rest res = 1 + min_op(s, start + 1, end) # if the first two characters are same if s[start] == s[start + 1]: res = min(res, 1 + min_op(s, start + 2, end)) # find the index of the next character same as the first for i in range(start + 2, end + 1): if s[start] == s[i]: res = min(res, min_op(s, start + 1, i - 1) + min_op(s, i + 1, end)) return res str = "2553432" print(min_op(str, 0, len(str) - 1))
C# // Recursive function to find the minimum operations // required to delete a string using System; class MinOperations { public static int MinOp(string str, int start, int end) { // if the string is empty if (start > end) return 0; // if the string has only one character if (start == end) return 1; // if string has only two characters and both are same if (start + 1 == end && str[start] == str[end]) return 1; // remove the first character and operate on the rest int res = 1 + MinOp(str, start + 1, end); // if the first two characters are same if (str[start] == str[start + 1]) res = Math.Min(res, 1 + MinOp(str, start + 2, end)); // find the index of the next character same as the first for (int i = start + 2; i <= end; i++) { if (str[start] == str[i]) { res = Math.Min(res, MinOp(str, start + 1, i - 1) + MinOp(str, i + 1, end)); } } return res; } public static void Main() { string str = "2553432"; Console.WriteLine(MinOp(str, 0, str.Length - 1)); } }
JavaScript // Recursive function to find the minimum operations // required to delete a string function minOp(str, start, end) { // if the string is empty if (start > end) return 0; // if the string has only one character if (start === end) return 1; // if string has only two characters and both are same if (start + 1 === end && str[start] === str[end]) return 1; // remove the first character and operate on the rest let res = 1 + minOp(str, start + 1, end); // if the first two characters are same if (str[start] === str[start + 1]) res = Math.min(res, 1 + minOp(str, start + 2, end)); // find the index of the next character same as the first for (let i = start + 2; i <= end; i++) { if (str[start] === str[i]) { res = Math.min(res, minOp(str, start + 1, i - 1) + minOp(str, i + 1, end)); } } return res; } const str = "2553432"; console.log(minOp(str, 0, str.length - 1));
[Expected Approach] – Using Memoization – O(n ^ 3) Time and O(n ^ 3) Space
The idea is to solve the problem recursively and use memoization to store the results of subproblems. Overlapping subproblems occur because the same substring is evaluated multiple times.
In each recursive call, we consider three operations:
- First, delete the first character and solve for the remaining substring;
- Second, if the first two characters are the same, delete both together and solve for the rest;
- Third, find another occurrence of the first character later in the string and combine the results of the two resulting subproblems.
Follow the below given steps to solve the problem:
- Create a 2d array memo[][] of order n * n to store the results of subproblems.
- For a substring defined by indices i to j,
- if i > j, return 0
- if i equals j, return 1.
- If the substring has two characters and they are the same, return 1.
- Otherwise, first compute 1 plus the result of solving the subproblem for the substring from i+1 to j.
- Then, if the first two characters are the same, consider 1 plus the result for the substring from i+2 to j.
- Finally, for every index k from i+2 to j where the character at index k equals the character at i, update the answer as the minimum of the current result and the sum of the results for the subproblems (i+1, k-1) and (k+1, j).
- Store and return the computed result in memo[i][j].
- At last return the value stored at memo[0][n-1].
Below is given the implementation:
C++ #include <bits/stdc++.h> using namespace std; // Recursive function to find the minimum // operations required to delete a string int minOp(string &str, int start, int end, vector<vector<int>> &memo) { // if the string is empty // no operations required if(start > end) return 0; // if the string has only one character // one operation required if(start == end) return 1; // if string has only two characters // and both the characters are same if(start + 1 == end && str[start] == str[end]) return 1; // if the result is already calculated if(memo[start][end] != -1) return memo[start][end]; // find results of all three operations // remove the first character and operate rest int res = 1 + minOp(str, start + 1, end, memo); // if the first two characters are same if(str[start] == str[start + 1]) res = min(res, 1 + minOp(str, start + 2, end, memo)); // find the index of the next character // which is same as the first character for(int i = start + 2; i <= end; i++) { if(str[start] == str[i]) { res = min(res, minOp(str, start + 1, i - 1, memo) + minOp(str, i + 1, end, memo)); } } return memo[start][end] = res; } // Function to find the minimum operations // to delete the string entirely int minOperations(string &str) { int n = str.size(); // to store the results of subproblems vector<vector<int>> memo(n, vector<int>(n, -1)); return minOp(str, 0, n - 1, memo); } int main() { string str = "2553432"; cout << minOperations(str); return 0; }
Java // Function to find the minimum operations // required to delete a string import java.util.*; class GfG { // Function to find the minimum operations // required to delete a string static int minOp(String str, int start, int end, int[][] memo) { // if the string is empty // no operations required if(start > end) return 0; // if the string has only one character // one operation required if(start == end) return 1; // if string has only two characters // and both the characters are same if(start + 1 == end && str.charAt(start) == str.charAt(end)) return 1; // if the result is already calculated if(memo[start][end] != -1) return memo[start][end]; // find results of all three operations // remove the first character and operate rest int res = 1 + minOp(str, start + 1, end, memo); // if the first two characters are same if(str.charAt(start) == str.charAt(start + 1)) res = Math.min(res, 1 + minOp(str, start + 2, end, memo)); // find the index of the next character // which is same as the first character for (int i = start + 2; i <= end; i++) { if (str.charAt(start) == str.charAt(i)) { res = Math.min(res, minOp(str, start + 1, i - 1, memo) + minOp(str, i + 1, end, memo)); } } memo[start][end] = res; return res; } // Function to find the minimum operations // to delete the string entirely static int minOperations(String str) { int n = str.length(); // to store the results of subproblems int[][] memo = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(memo[i], -1); } return minOp(str, 0, n - 1, memo); } public static void main(String[] args) { String str = "2553432"; System.out.println(minOperations(str)); } }
Python # Function to find the minimum operations # required to delete a string def minOp(str, start, end, memo): # if the string is empty # no operations required if start > end: return 0 # if the string has only one character # one operation required if start == end: return 1 # if string has only two characters # and both the characters are same if start + 1 == end and str[start] == str[end]: return 1 # if the result is already calculated if memo[start][end] != -1: return memo[start][end] # find results of all three operations # remove the first character and operate rest res = 1 + minOp(str, start + 1, end, memo) # if the first two characters are same if str[start] == str[start + 1]: res = min(res, 1 + minOp(str, start + 2, end, memo)) # find the index of the next character # which is same as the first character for i in range(start + 2, end + 1): if str[start] == str[i]: res = min(res, minOp(str, start + 1, i - 1, memo) \ + minOp(str, i + 1, end, memo)) memo[start][end] = res return res # Function to find the minimum operations # to delete the string entirely def minOperations(str): n = len(str) # to store the results of subproblems memo = [[-1 for _ in range(n)] for _ in range(n)] return minOp(str, 0, n - 1, memo) if __name__ == "__main__": str = "2553432" print(minOperations(str))
C# // Function to find the minimum operations required to delete a string using System; using System.Collections.Generic; class GfG { // Function to find the minimum operations // required to delete a string static int minOp(string str, int start, int end, int[][] memo) { // if the string is empty // no operations required if (start > end) return 0; // if the string has only one character // one operation required if (start == end) return 1; // if string has only two characters // and both the characters are same if (start + 1 == end && str[start] == str[end]) return 1; // if the result is already calculated if (memo[start][end] != -1) return memo[start][end]; // find results of all three operations // remove the first character and operate rest int res = 1 + minOp(str, start + 1, end, memo); // if the first two characters are same if (str[start] == str[start + 1]) res = Math.Min(res, 1 + minOp(str, start + 2, end, memo)); // find the index of the next character // which is same as the first character for (int i = start + 2; i <= end; i++) { if (str[start] == str[i]) { res = Math.Min(res, minOp(str, start + 1, i - 1, memo) + minOp(str, i + 1, end, memo)); } } memo[start][end] = res; return res; } // Function to find the minimum operations // to delete the string entirely static int minOperations(string str) { int n = str.Length; // to store the results of subproblems int[][] memo = new int[n][]; for (int i = 0; i < n; i++) { memo[i] = new int[n]; for (int j = 0; j < n; j++) { memo[i][j] = -1; } } return minOp(str, 0, n - 1, memo); } static void Main() { string str = "2553432"; Console.WriteLine(minOperations(str)); } }
JavaScript // Function to find the minimum operations // required to delete a string. function minOp(str, start, end, memo) { // if the string is empty // no operations required if (start > end) return 0; // if the string has only one character // one operation required if (start === end) return 1; // if string has only two characters // and both the characters are same if (start + 1 === end && str[start] === str[end]) return 1; // if the result is already calculated if (memo[start][end] !== -1) return memo[start][end]; // find results of all three operations // remove the first character and operate rest let res = 1 + minOp(str, start + 1, end, memo); // if the first two characters are same if (str[start] === str[start + 1]) res = Math.min(res, 1 + minOp(str, start + 2, end, memo)); // find the index of the next character // which is same as the first character for (let i = start + 2; i <= end; i++) { if (str[start] === str[i]) { res = Math.min(res, minOp(str, start + 1, i - 1, memo) + minOp(str, i + 1, end, memo)); } } memo[start][end] = res; return res; } // Function to find the minimum operations // to delete the string entirely function minOperations(str) { let n = str.length; let memo = new Array(n); for (let i = 0; i < n; i++) { memo[i] = new Array(n).fill(-1); } return minOp(str, 0, n - 1, memo); } let str = "2553432"; console.log(minOperations(str));
[Expected Approach – 2] – Using Tabulation – O(n ^ 3) Time and O(n ^ 3) Space
The idea is to solve the problem using dynamic programming by building a 2D table dp[][] where each entry dp[i][j] represents the minimum operations required to delete the substring s[i..j]. We calculate these values by considering the deletion of a single character, deleting two consecutive identical characters together, and combining the results from splitting at positions where the current character reoccurs.
Follow the below given steps:
- Create a 2d array dp[][] of order n * n to store the results of subproblems.
- For every substring length from 1 to n, iterate over all substrings s[i..j] (with j = i + len – 1).
- If the substring length is 1, set dp[i][j] = 1.
- Otherwise, set dp[i][j] initially to 1 + dp[i+1][j], representing deleting the ith character individually.
- If the first two characters are the same (s[i] == s[i+1]), update dp[i][j] to the minimum of its current value and 1 + dp[i+2][j].
- For every index k from i+2 to j, if s[i] equals s[k], update dp[i][j] as the minimum between its current value and the sum dp[i+1][k-1] + dp[k+1][j].
- Finally, dp[0][n-1] contains the answer, i.e. the minimum operations needed to delete the entire string.
Below is given the implementation:
C++ #include <bits/stdc++.h> using namespace std; // Function to find the minimum operations // to delete the string entirely int minOperations(string &str) { int n = str.size(); // create a 2d array dp[] to store // the results of subproblems vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0)); // loop for substring length we are considering for(int len = 1; len <= n; len++) { // loop with two variables i and j, denoting // starting and ending of substrings for(int i = 0, j = len - 1; j < n; i++, j++) { // If substring length is 1, then 1 step // will be needed if(len == 1) dp[i][j] = 1; else { // delete the ith char individually // and assign result for subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j]; // if current and next char are same, // choose min from current and subproblem // (i+2,j) if(str[i] == str[i + 1]) dp[i][j] = min(1 + dp[i + 2][j], dp[i][j]); // find the index of the next character // which is same as the first character for(int k = i + 2; k <= j; k++) { if(str[i] == str[k]) dp[i][j] = min(dp[i + 1][k - 1] + dp[k + 1][j], dp[i][j]); } } } } return dp[0][n - 1]; } int main() { string str = "2553432"; cout << minOperations(str); return 0; }
Java // Function to find the minimum operations // to delete the string entirely import java.util.*; class GfG { // Function to find the minimum operations // to delete the string entirely static int minOperations(String str) { int n = str.length(); // create a 2d array dp[] to store // the results of subproblems int[][] dp = new int[n + 1][n + 1]; for (int i = 0; i < n + 1; i++) { Arrays.fill(dp[i], 0); } // loop for substring length we are considering for (int L = 1; L <= n; L++) { // loop with two variables i and j, denoting // starting and ending of substrings for (int i = 0, j = L - 1; j < n; i++, j++) { // If substring length is 1, then 1 step // will be needed if (L == 1) dp[i][j] = 1; else { // delete the ith char individually // and assign result for subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j]; // if current and next char are same, // choose min from current and subproblem // (i+2,j) if (str.charAt(i) == str.charAt(i + 1)) dp[i][j] = Math.min(1 + dp[i + 2][j], dp[i][j]); // find the index of the next character // which is same as the first character for (int k = i + 2; k <= j; k++) { if (str.charAt(i) == str.charAt(k)) dp[i][j] = Math.min(dp[i + 1][k - 1] + dp[k + 1][j], dp[i][j]); } } } } return dp[0][n - 1]; } public static void main(String[] args) { String str = "2553432"; System.out.println(minOperations(str)); } }
Python # Function to find the minimum operations # to delete the string entirely. def minOperations(str): n = len(str) # create a 2d array dp[] to store # the results of subproblems dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)] # loop for substring length we are considering for L in range(1, n + 1): # loop with two variables i and j, denoting # starting and ending of substrings for i in range(0, n - L + 1): j = i + L - 1 # If substring length is 1, then 1 step # will be needed if L == 1: dp[i][j] = 1 else: # delete the ith char individually # and assign result for subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j] # if current and next char are same, # choose min from current and subproblem # (i+2,j) if str[i] == str[i + 1]: dp[i][j] = min(1 + dp[i + 2][j], dp[i][j]) # find the index of the next character # which is same as the first character for k in range(i + 2, j + 1): if str[i] == str[k]: dp[i][j] = min(dp[i + 1][k - 1] + dp[k + 1][j], dp[i][j]) return dp[0][n - 1] if __name__ == "__main__": str = "2553432" print(minOperations(str))
C# // Function to find the minimum operations // to delete the string entirely using System; using System.Collections.Generic; class GfG { // Function to find the minimum operations // to delete the string entirely static int minOp(string str, int start, int end, int[][] memo) { // This function is not used in this implementation. return 0; } // Function to find the minimum operations // to delete the string entirely static int minOperations(string str) { int n = str.Length; // create a 2d array dp[] to store // the results of subproblems int[][] dp = new int[n + 1][]; for (int i = 0; i < n + 1; i++) { dp[i] = new int[n + 1]; for (int j = 0; j < n + 1; j++) { dp[i][j] = 0; } } // loop for substring length we are considering for (int L = 1; L <= n; L++) { // loop with two variables i and j, denoting // starting and ending of substrings for (int i = 0, j = L - 1; j < n; i++, j++) { // If substring length is 1, then 1 step // will be needed if (L == 1) dp[i][j] = 1; else { // delete the ith char individually // and assign result for subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j]; // if current and next char are same, // choose min from current and subproblem // (i+2,j) if (str[i] == str[i + 1]) dp[i][j] = Math.Min(1 + dp[i + 2][j], dp[i][j]); // find the index of the next character // which is same as the first character for (int k = i + 2; k <= j; k++) { if (str[i] == str[k]) dp[i][j] = Math.Min(dp[i + 1][k - 1] + dp[k + 1][j], dp[i][j]); } } } } return dp[0][n - 1]; } static void Main() { string str = "2553432"; Console.WriteLine(minOperations(str)); } }
JavaScript // Function to find the minimum operations // to delete the string entirely. function minOperations(str) { let n = str.length; // create a 2d array dp[] to store // the results of subproblems. let dp = new Array(n + 1); for (let i = 0; i < n + 1; i++) { dp[i] = new Array(n + 1).fill(0); } // loop for substring length we are considering for (let L = 1; L <= n; L++) { // loop with two variables i and j, denoting // starting and ending of substrings for (let i = 0, j = L - 1; j < n; i++, j++) { // If substring length is 1, then 1 step // will be needed if (L === 1) { dp[i][j] = 1; } else { // delete the ith char individually // and assign result for subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j]; // if current and next char are same, // choose min from current and subproblem // (i+2,j) if (str[i] === str[i + 1]) dp[i][j] = Math.min(1 + dp[i + 2][j], dp[i][j]); // find the index of the next character // which is same as the first character for (let k = i + 2; k <= j; k++) { if (str[i] === str[k]) dp[i][j] = Math.min(dp[i + 1][k - 1] + dp[k + 1][j], dp[i][j]); } } } } return dp[0][n - 1]; } let str = "2553432"; console.log(minOperations(str));
Similar Reads
Palindrome String Coding Problems
A string is called a palindrome if the reverse of the string is the same as the original one. Example: âmadamâ, âracecarâ, â12321â. Properties of a Palindrome String:A palindrome string has some properties which are mentioned below: A palindrome string has a symmetric structure which means that the
2 min read
Palindrome String
Given a string s, the task is to check if it is palindrome or not. Example: Input: s = "abba"Output: 1Explanation: s is a palindrome Input: s = "abc" Output: 0Explanation: s is not a palindrome Using Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left)
14 min read
Check Palindrome by Different Language
Easy Problems on Palindrome
Sentence Palindrome
Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumer
9 min read
Check if actual binary representation of a number is palindrome
Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0âs are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
6 min read
Print longest palindrome word in a sentence
Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
14 min read
Count palindrome words in a sentence
Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
5 min read
Check if characters of a given string can be rearranged to form a palindrome
Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
14 min read
Lexicographically first palindromic string
Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message "no palindromic string". Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach: 1. Sort the string charact
13 min read