← Home

664. Strange Printer

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
664

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 664. Strange Printer, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming.

The notes already sitting in the source point us in the right direction:

  • DP
  • https://leetcode.com/problems/strange-printer/discuss/106810/Java-O(n3)-DP-Solution-with-Explanation-and-Simple-Optimization
  • time: O(N^3), space: O(N^2)

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are strangePrinter, tmp.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N^3), space: O(N^2)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//DP
02//https://leetcode.com/problems/strange-printer/discuss/106810/Java-O(n3)-DP-Solution-with-Explanation-and-Simple-Optimization
03//Runtime: 160 ms, faster than 31.75% of C++ online submissions for Strange Printer.
04//Memory Usage: 9.5 MB, less than 100.00% of C++ online submissions for Strange Printer.
05//time: O(N^3), space: O(N^2)
06class Solution {
07public:
08    int strangePrinter(string s) {
09        int n = s.size();
10        if(n == 0) return 0;
11        
12        vector<vector<int>> dp(n, vector(n, INT_MAX));
13        
14        for(int i = n-1; i >= 0; i--){
15            for(int dist = 0; i+dist < n; dist++){
16                int j = i+dist;
17                if(dist == 0){
18                    //base case: one char
19                    dp[i][j] = 1;
20                }else if(dist == 1){
21                    //base case: two chars
22                    /*
23                    if the two chars are the same, 
24                    we need just one print,
25                    o.w. we need two prints
26                    */
27                    dp[i][j] = 1 + (s[i] != s[j]);
28                }else{
29                    /*
30                    split s[i...j] into s[i...k] and s[k+1...j]
31                    note that k can be i!
32                    */
33                    for(int k = i; k <= j-1; k++){
34                        dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] - (s[k] == s[j]));
35                    }
36                }
37            }
38        }
39        
40        return dp[0][n-1];
41    }
42};
43
44//optimization, shorter s
45//https://leetcode.com/problems/strange-printer/discuss/106810/Java-O(n3)-DP-Solution-with-Explanation-and-Simple-Optimization
46//Runtime: 128 ms, faster than 43.25% of C++ online submissions for Strange Printer.
47//Memory Usage: 8.7 MB, less than 100.00% of C++ online submissions for Strange Printer.
48class Solution {
49public:
50    int strangePrinter(string s) {
51        if(s.size() == 0) return 0;
52        
53        string tmp(1, s[0]);
54        for(int i = 1; i < s.size(); i++){
55            if(s[i] != s[i-1]){
56                tmp += s[i];
57            }
58        }
59        s = tmp;
60        int n = s.size();
61        
62        vector<vector<int>> dp(n, vector(n, INT_MAX));
63        
64        for(int i = n-1; i >= 0; i--){
65            for(int dist = 0; i+dist < n; dist++){
66                int j = i+dist;
67                if(dist == 0){
68                    //base case: one char
69                    dp[i][j] = 1;
70                }else if(dist == 1){
71                    //base case: two chars
72                    /*
73                    if the two chars are the same, 
74                    we need just one print,
75                    o.w. we need two prints
76                    */
77                    dp[i][j] = 1 + (s[i] != s[j]);
78                }else{
79                    /*
80                    split s[i...j] into s[i...k] and s[k+1...j]
81                    note that k can be i!
82                    
83                    k>=i, k+1 <=j
84                    */
85                    for(int k = i; k <= j-1; k++){
86                        dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] - (s[k] == s[j]));
87                    }
88                }
89            }
90        }
91        
92        return dp[0][n-1];
93    }
94};

Cost

Complexity

Time
O(N^3), space: O(N^2)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.