Open In App

Minimum steps to delete a string after repeated deletion of palindrome substrings

Last Updated : 17 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 Python C# JavaScript

Output
2

[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 Python C# JavaScript

Output
2

[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 Python C# JavaScript

Output
2


Next Article

Similar Reads

three90RightbarBannerImg