There is a strange printer with the following two special properties:
The printer can only print a sequence of the same character each time.
At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
Given a string s, return the minimum number of turns the printer needed to print it.
Example 1:
Input: s = "aaabbb"
Output: 2
Explanation: Print "aaa" first and then print "bbb".
Example 2:
Input: s = "aba"
Output: 2
Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
Problem summary: There is a strange printer with the following two special properties: The printer can only print a sequence of the same character each time. At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters. Given a string s, return the minimum number of turns the printer needed to print it.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"aaabbb"
Example 2
"aba"
Related Problems
Remove Boxes (remove-boxes)
Strange Printer II (strange-printer-ii)
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #664: Strange Printer
class Solution {
public int strangePrinter(String s) {
final int inf = 1 << 30;
int n = s.length();
int[][] f = new int[n][n];
for (var g : f) {
Arrays.fill(g, inf);
}
for (int i = n - 1; i >= 0; --i) {
f[i][i] = 1;
for (int j = i + 1; j < n; ++j) {
if (s.charAt(i) == s.charAt(j)) {
f[i][j] = f[i][j - 1];
} else {
for (int k = i; k < j; ++k) {
f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j]);
}
}
}
}
return f[0][n - 1];
}
}
// Accepted solution for LeetCode #664: Strange Printer
func strangePrinter(s string) int {
n := len(s)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n)
for j := range f[i] {
f[i][j] = 1 << 30
}
}
for i := n - 1; i >= 0; i-- {
f[i][i] = 1
for j := i + 1; j < n; j++ {
if s[i] == s[j] {
f[i][j] = f[i][j-1]
} else {
for k := i; k < j; k++ {
f[i][j] = min(f[i][j], f[i][k]+f[k+1][j])
}
}
}
}
return f[0][n-1]
}
# Accepted solution for LeetCode #664: Strange Printer
class Solution:
def strangePrinter(self, s: str) -> int:
n = len(s)
f = [[inf] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
f[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
f[i][j] = f[i][j - 1]
else:
for k in range(i, j):
f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j])
return f[0][-1]
// Accepted solution for LeetCode #664: Strange Printer
/**
* [0664] Strange Printer
*
* There is a strange printer with the following two special properties:
*
* The printer can only print a sequence of the same character each time.
* At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
*
* Given a string s, return the minimum number of turns the printer needed to print it.
*
* Example 1:
*
* Input: s = "aaabbb"
* Output: 2
* Explanation: Print "aaa" first and then print "bbb".
*
* Example 2:
*
* Input: s = "aba"
* Output: 2
* Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
*
*
* Constraints:
*
* 1 <= s.length <= 100
* s consists of lowercase English letters.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/strange-printer/
// discuss: https://leetcode.com/problems/strange-printer/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn strange_printer(s: String) -> i32 {
let s = s.as_bytes();
let n = s.len();
match n {
0 => 0,
n @ _ => {
let mut dp = vec![vec![0; n + 1]; n + 1];
for len in 1..=n {
for i in 0..(n - len + 1) {
let j = i + len - 1;
dp[i][j] = 1 + dp[i + 1][j];
for k in (i + 1)..=j {
if s[k] == s[i] {
dp[i][j] = std::cmp::min(dp[i][j], dp[i][k - 1] + dp[k + 1][j]);
}
}
}
}
dp[0][n - 1]
}
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0664_example_1() {
let s = "aaabbb".to_string();
let result = 2;
assert_eq!(Solution::strange_printer(s), result);
}
#[test]
fn test_0664_example_2() {
let s = "aba".to_string();
let result = 2;
assert_eq!(Solution::strange_printer(s), result);
}
}
// Accepted solution for LeetCode #664: Strange Printer
function strangePrinter(s: string): number {
const n = s.length;
const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(1 << 30));
for (let i = n - 1; i >= 0; --i) {
f[i][i] = 1;
for (let j = i + 1; j < n; ++j) {
if (s[i] === s[j]) {
f[i][j] = f[i][j - 1];
} else {
for (let k = i; k < j; ++k) {
f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j]);
}
}
}
}
return f[0][n - 1];
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n^3)
Space
O(n^2)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.