#1312
Minimum Insertion Steps to Make a String Palindrome
HardStringDynamic ProgrammingDynamic ProgrammingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^n) | O(n²) |
| Space | O(n) | O(n²) |
💡
Intuition
Time O(n²)Space O(n²)
The optimal approach uses dynamic programming to find the longest palindromic subsequence (LPS) in the string. The minimum insertions required will be the difference between the string length and the LPS length.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a 2D DP array where dp[i][j] represents the length of the longest palindromic subsequence in the substring s[i:j].
- 2Step 2: Fill the DP table: if s[i] == s[j], then dp[i][j] = dp[i + 1][j - 1] + 2; otherwise, dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]).
- 3Step 3: The answer is the length of the string minus the value in dp[0][n-1], where n is the length of the string.
solution.py13 lines
1def min_insertions(s):
2 n = len(s)
3 dp = [[0] * n for _ in range(n)]
4 for i in range(n):
5 dp[i][i] = 1
6 for length in range(2, n + 1):
7 for i in range(n - length + 1):
8 j = i + length - 1
9 if s[i] == s[j]:
10 dp[i][j] = dp[i + 1][j - 1] + 2
11 else:
12 dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
13 return n - dp[0][n - 1]ℹ
Complexity note: The time complexity is O(n²) due to the nested loops filling the DP table. The space complexity is also O(n²) because we store results in a 2D array.
- 1Understanding the relationship between the longest palindromic subsequence and the minimum insertions needed.
- 2Dynamic programming can significantly reduce the complexity of problems involving subsequences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.