Palindrome Removal — LeetCode 1246 Python Solution

HardLeetCode PremiumArrayDynamic Programming
Problem
#1246
Reading time
3 min

The problem

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.

Example

Input
arr = [1,2]
Output
2

Python solution

Python
class Solution:
    def minimumMoves(self, arr: List[int]) -> int:
        n = len(arr)
        f = [[0] * n for _ in range(n)]
        for i in range(n):
            f[i][i] = 1
        for i in range(n - 2, -1, -1):
            for j in range(i + 1, n):
                if i + 1 == j:
                    f[i][j] = 1 if arr[i] == arr[j] else 2
                else:
                    t = f[i + 1][j - 1] if arr[i] == arr[j] else inf
                    for k in range(i, j):
                        t = min(t, f[i][k] + f[k + 1][j])
                    f[i][j] = t
        return f[0][n - 1]

Complexity

MeasureComplexity
TimeO(n^3)
SpaceO(n^2) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1246. Palindrome Removal is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1246. Palindrome Removal?
LeetCode 1246. Palindrome Removal is rated Hard on LeetCode.
What is the time complexity of LeetCode 1246. Palindrome Removal?
The Python solution on this page runs in O(n^3).
What is the space complexity of LeetCode 1246. Palindrome Removal?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 1246. Palindrome Removal cover?
LeetCode 1246. Palindrome Removal is tagged Array and Dynamic Programming on LeetCode.
Is LeetCode 1246. Palindrome Removal a premium problem?
Yes. LeetCode 1246. Palindrome Removal is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview