Strange Printer - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "aba"
Output: 2
💡 Note: First print 'a' at positions 0 and 2, then print 'b' at position 1. Total: 2 turns.
Example 2 — All Same Characters
$ Input: s = "aaabbb"
Output: 2
💡 Note: First print 'aaa' (positions 0-2), then print 'bbb' (positions 3-5). Total: 2 turns.
Example 3 — All Different
$ Input: s = "abcd"
Output: 4
💡 Note: Each character is different, so we need 4 separate printing operations.

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists of lowercase English letters.

Visualization

Tap to expand
Strange Printer Problem INPUT String s = "aba" a index 0 b index 1 a index 2 Printer Rules: 1. Print same char sequence at any position 2. New prints cover existing characters Goal: Min turns to print ALGORITHM STEPS 1 DP Table Setup dp[i][j] = min turns for s[i..j] 2 Base Case Single char: dp[i][i] = 1 3 Recurrence If s[i]==s[j]: merge ranges 4 Try All Splits Min of dp[i][k] + dp[k+1][j] DP Table for "aba": a b a a 1 2 2 b - 1 2 a - - 1 Answer: dp[0][2] = 2 FINAL RESULT Print Sequence: Turn 1: Print "aaa" a a a Turn 2: Print "b" at index 1 a b a Output: 2 OK - Minimum turns achieved s[0]==s[2] allows merging Key Insight: When s[i] == s[j], we can print s[i] to s[j] in one turn and fill middle chars later. This gives dp[i][j] = dp[i][j-1] since the last char is "free" when it matches the first. TutorialsPoint - Strange Printer | Optimal DP Solution
Asked in
Google 15 Amazon 8 Facebook 6
28.0K Views
Medium Frequency
~35 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen