829. Palindrome Erasing

Hard7.5 points estimatedArrayDynamic Programming4 hints

A jeweller keeps coloured beads in a row, the colour of each bead given by an integer in nums. In one move the jeweller may pick a contiguous block of beads whose colours read the same from left to right and from right to left, and take that whole block off the row. The beads on either side then slide together and the row stays contiguous.

Return the minimum number of moves needed to remove every bead. A single bead is a block by itself, so the answer never exceeds the length of the row. Aim for time O(n^3) and space O(n^2).

Example 1

Input:
nums = [6,2,9,2,6,4]
Output:
2
Explanation:

One move can erase 6 2 9 2 6 and a second the final 4, so the minimum is 2.

Example 2

Input:
nums = [3,8,3,8,3]
Output:
1
Explanation:

The whole row reads the same in both directions, so a single move clears it; the answer is 1.

Example 3

Input:
nums = [5,1,7,1,4,4]
Output:
3
Explanation:

Take out 1 7 1, then the lone 5, then 4 4; the minimum is 3 moves.

Constraints

1 ≤ nums.length ≤ 200

1 ≤ nums[i] ≤ 20

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n^3)
Space
O(n^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…