Palindrome Removal - Problem

Imagine you're cleaning up a messy array by removing palindromic sections piece by piece! ๐Ÿงน

You are given an integer array arr. In one move, you can select any palindromic subarray arr[i], arr[i + 1], ..., arr[j] where i <= j, and completely remove that subarray from the array. After removal, the remaining elements automatically shift together to fill the gap.

A palindromic subarray reads the same forwards and backwards. For example: [1], [2,2], [3,1,3], or [4,5,4].

Goal: Return the minimum number of moves needed to remove all elements from the array.

Example: For array [1,3,4,1,5], you could remove [4] first (1 move), then [3] (1 move), then [1,5,1] is not palindromic, so remove each [1] and [5] separately (2 more moves) = 4 total moves. But there might be a better strategy!

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,3,4,1,5]
โ€บ Output: 3
๐Ÿ’ก Note: Remove [4] (1 move), then [1,3,1] which becomes palindromic after adjacent elements merge (1 move), then [5] (1 move). Total: 3 moves.
example_2.py โ€” All Same Elements
$ Input: [1,1,1,1]
โ€บ Output: 1
๐Ÿ’ก Note: The entire array is palindromic, so we can remove it all in just 1 move.
example_3.py โ€” No Palindromes
$ Input: [1,2,3,4]
โ€บ Output: 4
๐Ÿ’ก Note: No palindromic subarrays of length > 1 exist, so we must remove each element individually. Total: 4 moves.

Constraints

  • 1 โ‰ค arr.length โ‰ค 100
  • 1 โ‰ค arr[i] โ‰ค 20
  • Each element is a positive integer
  • Array is not empty

Visualization

Tap to expand
Chocolate Bar Breaking Analogy13415Original Array: [1,3,4,1,5]Step 1: Mark Palindromic Sections[4][1][1]Step 2: Apply DP StrategyMove 1: Remove palindrome [4] โ†’ [1,3,1,5]Move 2: Remove palindrome [1,3,1] โ†’ [5]Move 3: Remove palindrome [5] โ†’ []Total: 3 moves (optimal!)๐ŸŽฏ Key InsightDP finds the optimal way to split intervals: either remove as palindrome or split optimally!
Understanding the Visualization
1
Identify Palindromes
Mark all palindromic subarrays in the input
2
Build DP Table
Fill table for increasing interval lengths
3
Choose Strategy
For each interval: remove entirely or split optimally
4
Get Result
dp[0][n-1] contains minimum moves for entire array
Key Takeaway
๐ŸŽฏ Key Insight: Use interval DP where each subproblem decides whether to remove a palindromic section entirely or split it optimally at some point k.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
28.5K Views
Medium Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen