Strange Printer — LeetCode 664 Python Solution
- Problem
- #664
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- s = "aaabbb"
- Output
- 2
- Explanation
- Print "aaa" first and then print "bbb".
Python solution
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]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^3) |
| Space | O(n^2) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 664. Strange Printer is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 664. Strange Printer?
- LeetCode 664. Strange Printer is rated Hard on LeetCode.
- What is the time complexity of LeetCode 664. Strange Printer?
- The Python solution on this page runs in O(n^3).
- What is the space complexity of LeetCode 664. Strange Printer?
- The Python solution on this page uses O(n^2) auxiliary space.
- What topics does LeetCode 664. Strange Printer cover?
- LeetCode 664. Strange Printer is tagged String and Dynamic Programming on LeetCode.