← Home

650. 2 Keys Keyboard

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

Let's make this one less mysterious. For 650. 2 Keys Keyboard, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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:

  • time: O(sqrt(n)), space: O(1)

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 minSteps.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • 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(sqrt(n)), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for 2 Keys Keyboard.
02//Memory Usage: 6 MB, less than 100.00% of C++ online submissions for 2 Keys Keyboard.
03//time: O(sqrt(n)), space: O(1)
04class Solution {
05public:
06    /*
07    our moves can be represented as [CP...PP][CP...P][CPP...P]...,
08    say their lengths are g_1, g_2, .... g_n.
09    
10    now suppose we have x 'A's on screen,
11    after [CP...PP] with length g_1,
12    there will be x * g_1 A's on screen,
13    so after all the moves: [CP...PP][CP...P][CPP...P]...,
14    we have x * g_1 * g_2 * ... * g_n 'A's,
15    and x is equal to 1, so we will have g_1 * g_2 * ... * g_n 'A's.
16    
17    to get exactly n 'A's, we can factor n to g_1 * g_2 * ... * g_n,
18    and it takes g_1 + g_2 + ... + g_n moves.
19    
20    now we need to prove that split n into g_1 * g_2 * ... * g_n 
21    only decreases the moves needed:
22    say g_i = p*q, we want g_i <= p+q -> p*q <= p+q
23    -> p*q-p-q <= 0 -> (p-1)*(q-1) <= 1,
24    and this is true when p >= 2 and q >= 2,
25    since our factorization stops when prime is equal to 2,
26    so this always holds
27    */
28    int minSteps(int n) {
29        int ans = 0;
30        int prime = 2;
31        
32        while(n > 1){
33            /*
34            if prime is a composite, 
35            it will skip this part,
36            because now n's smallest prime factor is larger than prime
37            */
38            while(n % prime == 0){
39                n /= prime;
40                ans += prime;
41            }
42            //try to find next prime
43            prime++;
44        }
45        
46        return ans;
47    }
48};
49
50//DP
51//https://leetcode.com/problems/2-keys-keyboard/discuss/105899/Java-DP-Solution
52//Runtime: 24 ms, faster than 35.04% of C++ online submissions for 2 Keys Keyboard.
53//Memory Usage: 6.8 MB, less than 100.00% of C++ online submissions for 2 Keys Keyboard.
54class Solution {
55public:
56    int minSteps(int n) {
57        //dp[i]: how many moves we need to take in order to get i A's
58        vector<int> dp(n+1, 0);
59        
60        //dp[1] is 0, 0 moves
61        for(int i = 2; i <= n; i++){
62            dp[i] = i;
63            for(int j = i-1; j >= 2; j--){
64                /*
65                i A's can be generated from j A's
66                by copy(1 move) and then paste i/j-1 times(i/j-1 moves),
67                so dp[i] is the move to get j A's(dp[j]) plus i/j moves
68                */
69                if(i % j == 0){
70                    dp[i] = dp[j] + i/j;
71                    break;
72                }
73            }
74        }
75        
76        return dp[n];
77    }
78};

Cost

Complexity

Time
O(sqrt(n)), space: O(1)
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.