Palindrome Removal - 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.

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.

Input & Output

Example 1 — Mixed Elements
$ Input: arr = [1,3,4,1,5]
Output: 3
💡 Note: Remove [4] (1 move), then remove [1,3,1] which becomes palindromic (1 move), finally remove [5] (1 move). Total: 3 moves.
Example 2 — All Same
$ Input: arr = [1,1,1,1]
Output: 1
💡 Note: The entire array is palindromic, so we can remove it in 1 move.
Example 3 — Single Element
$ Input: arr = [5]
Output: 1
💡 Note: Single element is palindromic, remove in 1 move.

Constraints

  • 1 ≤ arr.length ≤ 100
  • 1 ≤ arr[i] ≤ 100

Visualization

Tap to expand
Palindrome Removal: Minimum Moves to Clear Array13415Step 1: Remove [4] (1 move)131Step 2: Remove palindrome [1,3,1] (1 move)5Step 3: Remove [5] (1 move)Total: 3 moves
Understanding the Visualization
1
Input Array
Array [1,3,4,1,5] needs to be completely removed
2
Find Palindromes
Identify palindromic subarrays: [1], [3], [4], [1], [5], [1,3,1]
3
Optimal Partition
Best way: remove [4], then [1,3,1], then [5] = 3 moves
Key Takeaway
🎯 Key Insight: Use dynamic programming to find optimal palindromic partitioning
Asked in
Google 15 Microsoft 12 Amazon 8
18.5K Views
Medium Frequency
~35 min Avg. Time
892 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