Strange Printer — LeetCode 664 Python Solution

HardStringDynamic Programming
Problem
#664
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n^3)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview