Strange Printer (LeetCode 664): Solution and Explanation

Hard
String
Dynamic Programming

A printer can only print a run of one repeated character per turn, and each run can start and end anywhere, overwriting what was there. Find the fewest turns needed to produce a given string.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Start with the obvious upper bound: printing each character on its own takes one turn per character. Runs of identical adjacent characters can always be printed together, so the first simplification is to collapse them, turning "aabaa" into "aba". That does not change the answer and shrinks the input.

The real savings come from overwriting. To print "aba" you can lay down "aaa" in one turn and then print "b" over the middle, two turns total instead of three. In general, two equal characters that are far apart can share a single print, as long as everything between them is printed afterward on top. That observation suggests interval DP: let dp[i][j] be the fewest turns to print s[i..j].

Focus on the last character, s[j]. One option is to print it on its own, costing dp[i][j-1] + 1. The other option is that s[j] is printed in the same turn as some earlier s[k] with the same character, where i <= k < j. That long print covers k..j, so the middle s[k+1..j-1] is printed separately on top, and the left part s[i..k] already includes the shared turn. The cost is dp[i][k] + dp[k+1][j-1]. Taking the minimum across all such k gives the answer for the interval. Intervals are filled from short to long so that every subinterval is ready when needed.

Approach: Interval DP

  1. Remove consecutive duplicate characters, since a run always prints in one turn. Return 0 for an empty string.
  2. Create an n × n table dp and set dp[i][i] = 1 for every single character.
  3. For each interval length from 2 to n and each start i, set j = i + length - 1.
  4. Start with dp[i][j] = dp[i][j-1] + 1, printing s[j] in its own turn.
  5. For every k from i to j - 1 with s[k] == s[j], try dp[i][k] + dp[k+1][j-1], treating an empty middle as 0.
  6. Return dp[0][n-1].

Step-by-step example

s = "aabaa"
  1. Collapsing runs gives "aba", so n = 3 and dp[0][0] = dp[1][1] = dp[2][2] = 1.
  2. Length 2: dp[0][1] for "ab" is dp[0][0] + 1 = 2, and no earlier character matches 'b'. Likewise dp[1][2] = 2 for "ba".
  3. Length 3, interval "aba": the baseline is dp[0][1] + 1 = 3.
  4. At k = 0, s[0] == s[2] == 'a', so the two a's share a turn: dp[0][0] + dp[1][1] = 1 + 1 = 2.
  5. dp[0][2] = 2: print "aaaaa" across the whole string, then print "b" in the middle.

Code: Python, Java, C++

1class Solution:
2    def strangePrinter(self, s: str) -> int:
3        # Remove consecutive duplicates
4        s = ''.join(c for i, c in enumerate(s) if i == 0 or c != s[i-1])
5        n = len(s)
6        if n == 0:
7            return 0
8
9        # dp[i][j] = min turns to print s[i:j+1]
10        dp = [[0] * n for _ in range(n)]
11
12        for i in range(n):
13            dp[i][i] = 1
14
15        for length in range(2, n + 1):
16            for i in range(n - length + 1):
17                j = i + length - 1
18                dp[i][j] = dp[i][j-1] + 1
19                for k in range(i, j):
20                    if s[k] == s[j]:
21                        dp[i][j] = min(dp[i][j], dp[i][k] + (dp[k+1][j-1] if k+1 <= j-1 else 0))
22
23        return dp[0][n-1]

Time and space complexity

Time

O(n³)

There are O(n²) intervals and each one tries up to n split points k.

Space

O(n²)

The DP table stores one value per interval.

Other approaches

Top-down memoized recursion (time O(n³), space O(n²))

Define solve(i, j) with the same choices: print the first character alone, or let it share a turn with every later matching character. Memoize on (i, j). It mirrors the reasoning closely and has the same cost, though recursion depth can reach n.

Common mistakes

  • Assuming the answer is the number of distinct runs. Overwriting can merge non-adjacent equal characters, so "aba" needs 2 turns, not 3.
  • Writing the shared-turn case as dp[i][k-1] + dp[k][j-1] or similar off-by-one variants that double count the shared character.
  • Filling the table by increasing i instead of by interval length, which reads subintervals before they are computed.
  • Forgetting the empty middle case when k + 1 > j - 1, which in some languages reads an invalid cell.

Frequently asked questions

Why does Strange Printer focus on the last character?

The last character is either printed alone or shares a turn with an earlier equal character. Considering those two cases covers every optimal strategy and splits the interval into independent smaller ones.

Why is the time complexity of Strange Printer O(n³)?

The table has one entry for every pair (i, j), which is O(n²) intervals. Each interval looks at up to n split points k, and every split is a constant-time lookup, so the total is cubic. With n at most 100 that is about a million steps.

Why remove consecutive duplicates first?

A run of identical characters can always be printed in the same turn, so collapsing it never changes the answer. It reduces n, which matters for an O(n³) algorithm.

Is Strange Printer similar to Remove Boxes or Burst Balloons?

Yes. All three are interval DP problems where you choose how a boundary element interacts with an element inside the interval. Strange Printer is the simplest of the group.