Strange Printer solution explained
Strange Printer is an interval DP problem: let turns(i, j) be the fewest strokes that print s[i..j]. Either the first character gets its own stroke, giving 1 + turns(i + 1, j), or its stroke stretches to a later matching character k and is shared, giving turns(i + 1, k - 1) + turns(k, j). Taking the minimum over every k runs in O(n³) time and O(n²) memory.
By Evin JohnPublished 8 min read
The printer, described plainly
A printer works on a row of blank cells. In one turn it picks a single letter and a contiguous stretch of cells, and paints that letter over the whole stretch, replacing anything underneath. Later turns can paint over earlier ones. Given the string you want to end up with, return the smallest number of turns that produces it exactly.
Overwriting is the whole point. A wide stroke laid down early acts as a background, and narrow strokes on top fill in the different letters. The question is which letters deserve a long background stroke and which are cheaper to print alone.
| Target | Turns | One plan that reaches it |
|---|---|---|
| kkk | 1 | One stroke of k across all three cells |
| ttuutt | 2 | t across all six, then u over the middle two |
| pqrp | 3 | p across all four, then q, then r |
| mnmn | 3 | m across the first three cells, n at position 1, then n at the end |
| abcabc | 5 | a across the first four cells, then b, c, b and c one at a time |
Clarify the alphabet (lowercase letters only?), whether an empty string is possible, and the maximum length. The length matters because the standard solution is cubic, which is comfortable for a few hundred characters and not for a hundred thousand.
Why interviewers like it
Most candidates first try to count something: runs of equal letters, or distinct letters. Both are wrong, and the interviewer gets to watch you find the counterexample. ttuutt has three runs but needs only two turns. mnmn has two distinct letters but needs three. The problem then asks you to invent the right subproblem, which is harder here than in textbook interval DP because the split is conditional: you only merge across a point where the letters agree. It tends to appear in harder onsite rounds rather than screens.
Finding the recurrence
Focus on the range s[i..j] and its first letter, s[i]. Some stroke paints s[i] in the final picture. We can assume that stroke starts at position i and is laid down before anything else in the range, since moving it earlier never hurts: anything painted on top still wins.
- Option 1: the stroke covers only position i. Then the rest of the range is an independent problem, and the cost is 1 + turns(i + 1, j).
- Option 2: the stroke reaches a later position k where s[k] equals s[i]. Everything strictly between, s[i + 1..k - 1], gets printed on top of that background as its own subproblem. From position k onward, the letter at k is already covered by the shared stroke, so the cost of s[k..j] already pays for that stroke once. Total: turns(i + 1, k - 1) + turns(k, j), with no extra 1.
Take the minimum over option 1 and every matching k. A single letter costs 1, and an empty range costs 0. Notice that k only ranges over positions where the letters match; splitting anywhere else would just add two independent costs, which option 1 already covers.
Slow approach: recursion without a cache
The recurrence translates line for line into a recursive function. It is right, and on short strings it is fast enough to use as a reference, but it revisits the same (i, j) ranges again and again. With many repeated letters the call tree explodes exponentially.
def printer_slow(s):
def go(i, j):
if i > j:
return 0
best = 1 + go(i + 1, j) # s[i] printed on its own
for k in range(i + 1, j + 1):
if s[k] == s[i]: # stretch the stroke for s[i] to k
best = min(best, go(i + 1, k - 1) + go(k, j))
return best
return go(0, len(s) - 1)Main approach: squash runs, then a bottom-up table
Two changes make it efficient. First, collapse each run of equal neighbors to one letter, because a run is always printed by the same stroke; ttuutt becomes tut, which shortens the input and means a matching k is never the very next index. Second, store turns[i][j] for every pair. Filling i from the right end toward the left, and j from i upward, guarantees that turns[i + 1][...] and turns[k][j] are ready when needed.
def strange_printer(s):
t = []
for ch in s: # a run of one letter always prints in one stroke
if not t or t[-1] != ch:
t.append(ch)
n = len(t)
if n == 0:
return 0
turns = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
turns[i][i] = 1
for j in range(i + 1, n):
best = turns[i + 1][j] + 1
for k in range(i + 2, j + 1):
if t[k] == t[i]:
best = min(best, turns[i + 1][k - 1] + turns[k][j])
turns[i][j] = best
return turns[0][n - 1]function strangePrinter(s) {
const t = [];
for (const ch of s) {
if (t.length === 0 || t[t.length - 1] !== ch) t.push(ch);
}
const n = t.length;
if (n === 0) return 0;
const turns = Array.from({ length: n }, () => new Array(n).fill(0));
for (let i = n - 1; i >= 0; i--) {
turns[i][i] = 1;
for (let j = i + 1; j < n; j++) {
let best = turns[i + 1][j] + 1;
for (let k = i + 2; k <= j; k++) {
if (t[k] === t[i]) {
best = Math.min(best, turns[i + 1][k - 1] + turns[k][j]);
}
}
turns[i][j] = best;
}
}
return turns[0][n - 1];
}Trace pqrp. No runs to squash. For the full range, option 1 is 1 + turns(qrp) = 1 + 3 = 4. The only matching k is the last p, which gives turns(qr) + turns(p) = 2 + 1 = 3. The answer is 3: a background of p, then q and r on top.
Complexity
| Approach | Time | Memory | Notes |
|---|---|---|---|
| Recursion, no cache | Exponential in the worst case | O(n) stack | Good as a test oracle on tiny inputs |
| Recursion with a cache | O(n³) | O(n²) plus stack | Python may need a higher recursion limit |
| Bottom-up table | O(n³) | O(n²) | The version to present |
In practice the inner loop only touches positions with a matching letter, so strings with few repeats run much faster than the bound. Squashing runs also lowers n before the cubic work starts.
Edge cases
- Empty string: zero turns. Guard it before allocating the table.
- One letter repeated, like kkk: one turn, and squashing reduces it to a single character.
- No letter repeats, like pqrs: every letter needs its own stroke, so the answer equals the length.
- Palindromes such as xyzyx: the outer letters share a stroke, and the inner part is solved on top, giving 3.
- Long inputs with a small alphabet: lots of matching k values, which is where the cubic bound is actually felt.
Mistakes that come up
- Counting runs or distinct letters. Both fail on short cases. Test any counting idea on ttuutt and mnmn before trusting it.
- Adding 1 in the merge branch. turns(k, j) already pays for the stroke that starts at k. Adding another 1 double-counts it, and the answers come out too high.
- Splitting at every k. Trying every split point like matrix chain gives turns(i, k) + turns(k + 1, j), which can never merge strokes across the split and so overcounts.
- Filling the table left to right in i. turns[i][j] needs turns[i + 1][...], so i has to go from the end backward.
- Skipping the brute-force check. The merge rule is subtle. A tiny breadth-first search over printer states is the fastest way to catch an off-by-one.
Saying it out loud
Fictional example
- Candidate
- Counting runs fails on t-t-u-u-t-t, which needs two turns, so I need a real subproblem. I'll use turns(i, j) for the substring between i and j.
- Candidate
- The first letter's stroke either stops right there, costing one plus the rest, or it reaches a later copy of the same letter at k. Then the middle is printed on top, and the part from k on already includes that stroke.
- Candidate
- I'll squash repeated neighbors first, fill the table with i going backward, and that gives cubic time and quadratic space. Let me check it on p-q-r-p, which should be three.
Neighbors in this set
Minimum Score Triangulation of Polygon uses an unconditional split point, which makes a nice contrast with the matching-letter split here. Remove Boxes pushes the same merge-equal-items idea further by carrying a count of attached boxes as a third index. For the broader topic list, see algorithm interview questions.
Rehearsing it with Natively
A tricky recurrence like this one is a good fit for practice with Natively. Take a screenshot of the problem and it reads the text and drafts an approach with code in its overlay, so you can compare the merge rule with your own once you have committed to an answer. It can also transcribe a timed mock session on your computer, which shows whether you tested a counting idea before discarding it. More on an AI interview assistant for Mac and Windows.
Questions people ask
What is the approach for the Strange Printer problem?
Interval dynamic programming. turns(i, j) is the fewest strokes for s[i..j]: either print s[i] alone for 1 + turns(i + 1, j), or extend its stroke to a later matching letter k for turns(i + 1, k - 1) + turns(k, j). Take the minimum.
What is the time complexity of Strange Printer?
O(n³) time and O(n²) space for a string of length n, after collapsing runs of the same letter. Strings with few repeated letters run well below that bound.
Why doesn't counting runs of letters work?
Because strokes can overlap. ttuutt has three runs but needs only two turns: one t across everything, then u on top. The number of turns depends on which strokes can be shared, not on how many runs there are.
Why is there no +1 when the stroke is extended to k?
The subproblem turns(k, j) already counts the stroke that prints s[k]. Since s[i] equals s[k], one stroke covers both, so adding 1 again would count it twice.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
