Skip to content
Problem 664 · LeetCode 664(opens in a new tab)

Strange Printer

HardDynamic programming

A printer works in turns. In one turn it picks a stretch of positions and fills all of them with one letter, painting over anything already there.

Given the string s, return the fewest turns needed to produce exactly s on a blank line.

Example 1

Input:  s = "abca"
Output: 3
Why:    paint aaaa, then b at index 1, then c at index 2
2 more examples and the constraints

Example 2

Input:  s = "ccdd"
Output: 2
Why:    one turn for cc, one for dd

Example 3

Input:  s = "abab"
Output: 3
Why:    paint aaa over 0..2, then b at 1, then b at 3

Constraints

  • 1 ≤ length of s ≤ 100
  • s has only lowercase English letters

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursion with a memoO(n³)
  2. Bottom-up interval tableO(n³)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100 lettersVerdict
Recursion with a memoO(n³)
Clear; pays for recursive calls
Bottom-up interval tableO(n³)
Best; same work in plain loops

n = length of s.

Edge cases to test

  • One letter. "z" takes 1 turn.
  • All the same letter. "aaaa" takes 1 turn, however long.
  • All different. "abcdef" takes 6 turns: nothing can be shared.
  • Letter wraps around others. "abcba" takes 3: a over everything, b over 1..3, then c.
  • Interleaved letters. "abab" takes 3, not 2: the two letters cross, so one of them needs two turns.

Common mistakes

  • Counting the shared turn twice by adding 1 to both parts of the split.
  • Greedily painting the most common letter first, which fails on strings like "abab".
  • Filling the table in the wrong order, so dp[i + 1][j] is read before it is set.

How to talk through it

  1. 1Clarify. Can one turn paint over letters already printed? Is the line blank at the start?
  2. 2Pick the subproblem. Fewest turns for a substring s[i..j]: the classic interval DP shape.
  3. 3Focus on the first letter. It gets its own turn, or shares one with a later equal letter at k, which splits the range.
  4. 4Write the table. Fill i from the bottom up and j to the right; O(n³) for n ≤ 100 is about 170,000 steps.
  5. 5Test out loud. Run "abca", "aaaa" and "abab" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?