Strange Printer (LeetCode 664): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Remove consecutive duplicate characters, since a run always prints in one turn. Return 0 for an empty string.
- Create an n × n table
dpand setdp[i][i] = 1for every single character. - For each interval length from 2 to n and each start
i, setj = i + length - 1. - Start with
dp[i][j] = dp[i][j-1] + 1, printings[j]in its own turn. - For every
kfromitoj - 1withs[k] == s[j], trydp[i][k] + dp[k+1][j-1], treating an empty middle as 0. - Return
dp[0][n-1].
Step-by-step example
s = "aabaa"
- Collapsing runs gives "aba", so n = 3 and
dp[0][0] = dp[1][1] = dp[2][2] = 1. - Length 2:
dp[0][1]for "ab" isdp[0][0] + 1 = 2, and no earlier character matches 'b'. Likewisedp[1][2] = 2for "ba". - Length 3, interval "aba": the baseline is
dp[0][1] + 1 = 3. - 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. 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]1class Solution {
2 public int strangePrinter(String s) {
3 StringBuilder sb = new StringBuilder();
4 for (int i = 0; i < s.length(); i++) {
5 if (i == 0 || s.charAt(i) != s.charAt(i-1)) {
6 sb.append(s.charAt(i));
7 }
8 }
9 s = sb.toString();
10 int n = s.length();
11 if (n == 0) return 0;
12
13 int[][] dp = new int[n][n];
14
15 for (int i = 0; i < n; i++) {
16 dp[i][i] = 1;
17 }
18
19 for (int len = 2; len <= n; len++) {
20 for (int i = 0; i <= n - len; i++) {
21 int j = i + len - 1;
22 dp[i][j] = dp[i][j-1] + 1;
23 for (int k = i; k < j; k++) {
24 if (s.charAt(k) == s.charAt(j)) {
25 dp[i][j] = Math.min(dp[i][j], dp[i][k] + (k+1 <= j-1 ? dp[k+1][j-1] : 0));
26 }
27 }
28 }
29 }
30
31 return dp[0][n-1];
32 }
33}1class Solution {
2public:
3 int strangePrinter(string s) {
4 string t;
5 for (int i = 0; i < s.size(); i++) {
6 if (i == 0 || s[i] != s[i-1]) t += s[i];
7 }
8 s = t;
9 int n = s.size();
10 if (n == 0) return 0;
11
12 vector<vector<int>> dp(n, vector<int>(n, 0));
13
14 for (int i = 0; i < n; i++) {
15 dp[i][i] = 1;
16 }
17
18 for (int len = 2; len <= n; len++) {
19 for (int i = 0; i <= n - len; i++) {
20 int j = i + len - 1;
21 dp[i][j] = dp[i][j-1] + 1;
22 for (int k = i; k < j; k++) {
23 if (s[k] == s[j]) {
24 dp[i][j] = min(dp[i][j], dp[i][k] + (k+1 <= j-1 ? dp[k+1][j-1] : 0));
25 }
26 }
27 }
28 }
29
30 return dp[0][n-1];
31 }
32};Time and space complexity
O(n³)
There are O(n²) intervals and each one tries up to n split points k.
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
iinstead 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.