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: Transform "aba" with Minimum TurnsInput StringabaTurn 1: Print 'a'a?aTurn 2: Print 'b'abKey insight: Print matching characters (a,a) in one turnThen cover the middle position with 'b' in second turnResult: 2 turns (optimal)
Understanding the Visualization
1
Input String
String 'aba' needs to be printed
2
Smart Printing
Print matching characters together
3
Minimum Turns
Find the optimal printing sequence
Key Takeaway
🎯 Key Insight: When characters at the ends match, we can print them together and solve the middle part separately, leading to optimal substructure for dynamic programming.
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