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

Problem statement

Given a string containing characters as integers only. We need to delete all character of this string in a minimum number of steps where in one step we can delete the substring which is a palindrome. After deleting a substring remaining parts are concatenated.


If input string is 3441213 then minimum 2 steps required

  • First remove 121 from string. Now remaining string is 3443
  • Remove remaining string as it’s palindrome


We can use dynamic programming to solve this problem

1. Let dp[i][j] denotes the number of steps it takes to delete the substring s[i, j]
2. Each character will be deleted alone or as part of some substring so in the first case we will delete the character itself and call subproblem (i+1, j)
3. In the second case we will iterate over all occurrence of the current character in right side, if K is the index of one such occurrence then the problem will reduce to two subproblems (i+1, K – 1) and (K+1, j)
4. We can reach to this subproblem (i+1, K-1) because we can just delete the same character and call for mid substring
5. We need to take care of a case when first two characters are same in that case we can directly reduce to the subproblem (i+2, j)


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMinRequiredSteps(string str) {
   int n = str.length();
   int dp[n + 1][n + 1];
   for (int i = 0; i <= n; i++) {
      for (int j = 0; j <= n; j++) {
         dp[i][j] = 0;
   for (int len = 1; len <= n; len++) {
      for (int i = 0, j = len - 1; j < n; i++, j++) {
         if (len == 1)
            dp[i][j] = 1;
         else {
            dp[i][j] = 1 + dp[i + 1][j];
            if (str[i] == str[i + 1]) {
               dp[i][j] = min(1 + dp[i+ 2][j], dp[i][j]);
            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 = "3441213";
   cout << "Minimum required steps: " <<
   getMinRequiredSteps(str) << endl;
   return 0;

When you compile and execute above program. It generates following output


Minimum required steps: 2

Updated on: 23-Dec-2019


Kickstart Your Career

Get certified by completing the course

Get Started