Similar Problems

Similar Problems not available

Minimum Number Of Moves To Make Palindrome - Leetcode Solution

Companies:

LeetCode:  Minimum Number Of Moves To Make Palindrome Leetcode Solution

Difficulty: Hard

Topics: greedy string two-pointers  

The problem statement is as follows:

Given a string s, return the minimum number of moves required to make s a palindrome. A move is defined as inserting a character at any position, deleting any character from any position, or replacing any character.

For example: Input: "abcd" Output: 3 Explanation: Insert 'b' and 'c' to make "bacd" then replace 'a' with 'b'.

To solve this problem, we can use dynamic programming. We can create a 2D array dp where dp[i][j] represents the minimum number of moves required to make the substring s[i...j] a palindrome.

We can initialize the diagonal elements of the array to 0 because a single character string is already a palindrome. For all other elements dp[i][j], we can use the following recurrence relation based on the length of the substring:

if s[i] == s[j]: dp[i][j] = dp[i+1][j-1] else: dp[i][j] = min(dp[i+1][j], dp[i][j-1], dp[i+1][j-1]) + 1

Here, if the first and last characters of the substring are same, we do not need to make any additional moves. So, we can just look at the minimum moves required for the remaining substring by excluding the first and last characters i.e. dp[i+1][j-1]. If they are different, we have three options - we can either insert a character at the beginning (dp[i+1][j]), delete a character from the end (dp[i][j-1]), or replace the first or last character (dp[i+1][j-1]). We can choose the option that gives us the minimum number of moves and add 1 to it.

At the end, the value at dp[0][n-1] gives us the minimum number of moves required to make the whole string s a palindrome.

Here is the Python implementation of the solution:

def minMovesToPalindrome(s): n = len(s) dp = [[0] * n for _ in range(n)]

for gap in range(1, n):
    for i in range(n-gap):
        j = i + gap
        
        if s[i] == s[j]:
            dp[i][j] = dp[i+1][j-1]
        else:
            dp[i][j] = min(dp[i+1][j], dp[i][j-1], dp[i+1][j-1]) + 1

return dp[0][n-1]

Example

s = "abcd" print(minMovesToPalindrome(s)) # Output: 3

Time Complexity: O(n^2) Space Complexity: O(n^2)

Minimum Number Of Moves To Make Palindrome Solution Code

1