<p>Given a string <code>s</code>. In one step you can insert any character at any index of the string.</p>

<p>Return <em>the minimum number of steps</em> to make <code>s</code>&nbsp;palindrome.</p>

<p>A&nbsp;<b>Palindrome String</b>&nbsp;is one that reads the same backward as well as forward.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;zzazz&quot;
<strong>Output:</strong> 0
<strong>Explanation:</strong> The string &quot;zzazz&quot; is already palindrome we do not need any insertions.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;mbadm&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> String can be &quot;mbdadbm&quot; or &quot;mdbabdm&quot;.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;leetcode&quot;
<strong>Output:</strong> 5
<strong>Explanation:</strong> Inserting 5 characters the string becomes &quot;leetcodocteel&quot;.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 500</code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

class Solution {
public:
    int minInsertions(string s) {
        // If the string is already a palindrome, return 0
        if (is_palindrome(s)) {
            return 0; 
        }

        int n = s.size();
        // Initialize the dp table with -1 to indicate uncomputed subproblems
        vector<vector<int>> dp(n, vector<int>(n, -1)); 

        // Start the helper function
        return minInsertionsHelper(s, 0, n - 1, dp);  
    }

    // Helper function to calculate the minimum insertions with memoization
    int minInsertionsHelper(string &s, int left, int right, vector<vector<int>>& dp) {
        // Base case: if left >= right, no insertions are needed
        if (left >= right) {
            return 0; 
        }

        // If the result is already computed, return it
        if (dp[left][right] != -1) {
            return dp[left][right]; 
        }

        // If the characters match, move both pointers inward
        if (s[left] == s[right]) {
            dp[left][right] = minInsertionsHelper(s, left + 1, right - 1, dp);
        } else {
            // If they don't match, try inserting at left or right and take the minimum
            dp[left][right] = min(minInsertionsHelper(s, left + 1, right, dp), 
                                  minInsertionsHelper(s, left, right - 1, dp)) + 1;
        }

        return dp[left][right]; 
    }

    // Function to check if the string is a palindrome
    bool is_palindrome(const string &s) {
        int left = 0, right = s.size() - 1;
        while (left < right) {
            if (s[left] != s[right]) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
};

25100