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 - Optimal Solution INPUT Integer Array arr[] 1 i=0 3 i=1 4 i=2 1 i=3 5 i=4 arr = [1, 3, 4, 1, 5] Length = 5 Goal: Remove all elements using minimum palindrome removals dp[i][j] = min moves for arr[i..j] Base: dp[i][i] = 1 If arr[i]==arr[j]: dp[i+1][j-1] ALGORITHM STEPS 1 Initialize DP Table dp[i][i]=1, single element is palindrome (1 move) 2 Fill DP by Length For len=2 to n, compute dp[i][j] for each subarray 3 Check Endpoints If arr[i]==arr[j], can use dp[i+1][j-1] (merge ends) 4 Try All Splits dp[i][j] = min(dp[i][k] + dp[k+1][j]) for all k Example Trace: Move 1: Remove [1,3,4,1] Move 2: Remove [3,4] Move 3: Remove [5] Total: 3 moves FINAL RESULT Removal Sequence: Move 1: Remove [1,3,4,1] [1,3,4,1,5] --> [5] Move 2: Remove [3,4] (inner palindrome pair) Move 3: Remove [5] [5] --> [] Output: 3 OK - Minimum Moves Key Insight: When arr[i] == arr[j], we can remove them together with the middle portion in one extended palindrome. The DP recurrence: dp[i][j] = min(dp[i][k] + dp[k+1][j]) for splits, or dp[i+1][j-1] if endpoints match. Time: O(n^3) | Space: O(n^2) for the DP table storing minimum moves for each subarray. TutorialsPoint - Palindrome Removal | Optimal DP Solution
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