Palindrome Removal Problem
Description
LeetCode Problem 1246.
You are given an integer array arr.
In one move, you can select a palindromic subarray arr[i], arr[i + 1], ..., arr[j] where i <= j, and remove that subarray from the given array. Note that after removing a subarray, the elements on the left and on the right of that subarray move to fill the gap left by the removal.
Return the minimum number of moves needed to remove all numbers from the array.
Example 1:
Input: arr = [1,2]
Output: 2
Example 2:
Input: arr = [1,3,4,1,5]
Output: 3
Explanation: Remove [4] then remove [1,3,1] then remove [5].
Constraints:
1 <= arr.length <= 1001 <= arr[i] <= 20
Solution
Approach: Interval Dynamic Programming
Let f[i][j] be the fewest moves to remove the subarray arr[i..j]. One element takes one move: f[i][i] = 1. For a longer range, look at what happens to arr[i]:
- It is not removed in the same move as
arr[j]: then the range splits intoarr[i..k]andarr[k+1..j]that are cleared separately, for somekwithi <= k < j. This givesf[i][k] + f[k + 1][j]. - It is removed in the same move as
arr[j]: that needsarr[i] == arr[j]. Clear the insidearr[i+1..j-1]as well as possible, and addarr[i]andarr[j]to its last move: a palindrome with the same number added on both sides is still a palindrome. So this costsf[i + 1][j - 1]moves, and just1when the two are neighbours.
f[i][j] is the smallest of these options, and the answer is f[0][n - 1]. Shorter ranges must be ready first, so i goes from right to left and j from i + 1 to the right.
The tricky part is the second case: the two equal ends cost nothing extra, because they ride along with a move that happens anyway. That is why [1, 3, 4, 1, 5] needs only 3 moves: remove 4, then 1, 3, 1, then 5.
Complexity: O(n3) time and O(n2) space.
class Solution:
def minimumMoves(self, arr: List[int]) -> int:
n = len(arr)
# f[i][j] = fewest moves to remove arr[i..j]
f = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
f[i][i] = 1
for j in range(i + 1, n):
if arr[i] == arr[j]:
# arr[i] and arr[j] go away together with the last move on arr[i+1..j-1]
best = f[i + 1][j - 1] if i + 1 < j else 1
else:
best = n
for k in range(i, j): # or remove arr[i..k] and arr[k+1..j] separately
if f[i][k] + f[k + 1][j] < best:
best = f[i][k] + f[k + 1][j]
f[i][j] = best
return f[0][n - 1]