Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

650. 2 Keys Keyboard - Leetcode Solution

Problem Description

The 2 Keys Keyboard problem from Leetcode asks you to determine the minimum number of steps required to generate exactly n 'A' characters on a notepad, starting with just one 'A'. The only two operations you can perform are:

  • Copy All: Copy all of the characters currently on the notepad (the entire string).
  • Paste: Paste the last copied string onto the notepad.

You can perform these operations as many times as needed. The goal is to reach exactly n 'A's using the minimum number of steps. Each operation counts as one step.

Constraints:

  • 1 <= n <= 1000
  • Only two operations are allowed: Copy All and Paste
  • You start with exactly one 'A'

Thought Process

At first glance, it might seem like you should simply paste as many times as possible, but the challenge is to minimize the number of steps. If you always copy and paste at every opportunity, you might not be efficient. For example, reaching 9 'A's by copying at every step is not optimal.

The key insight is that the Copy All operation is powerful, but should only be used when it allows you to multiply your current count in a way that gets you closer to n quickly. This leads to thinking about the problem in terms of factorization—breaking n into factors and using those to guide when to copy and paste.

The brute-force approach would be to try all possible sequences of operations, but this is inefficient. Instead, we can optimize by observing that every time we "build up" to a factor of n, we can copy and paste that chunk repeatedly to reach n in fewer steps.

Solution Approach

The most efficient way to solve this problem is to use the prime factorization of n. Here's how the algorithm works:

  1. Prime Factorization: For every factor of n (starting from 2), while n is divisible by that factor, add the factor to a running total, and divide n by that factor.
  2. Interpretation: Each time we find a factor f, it represents a sequence where we perform a "Copy All" followed by f-1 "Paste" operations. So, the sum of all such factors gives the minimum number of steps.
  3. Why it works: The process mimics building up the string by repeatedly copying and pasting chunks, where each chunk's size is determined by the factors of n.

Example: To get 9 'A's, factor 9 as 3 x 3. The optimal sequence is: Copy (step 1), Paste, Paste (steps 2-3) to get 3 'A's, then Copy (step 4), Paste, Paste (steps 5-6) to get 9 'A's. Total steps: 6.

Algorithm Steps:

  • Initialize ans = 0.
  • For each integer i from 2 up to n:
    • While n is divisible by i:
      • Add i to ans.
      • Divide n by i.
  • Return ans as the minimum number of steps.

Example Walkthrough

Let's walk through an example with n = 8:

  1. Prime factors of 8 are 2, 2, and 2.
  2. First, copy at 1 'A', paste to get 2 'A's (steps: Copy, Paste).
  3. Copy at 2 'A's, paste to get 4 'A's (steps: Copy, Paste).
  4. Copy at 4 'A's, paste to get 8 'A's (steps: Copy, Paste).
  5. Total steps: Copy, Paste, Copy, Paste, Copy, Paste = 6 steps.

The algorithm adds up the factors: 2 + 2 + 2 = 6 steps, matching our manual process.

Time and Space Complexity

  • Brute-force: Would try all possible operation sequences, leading to exponential time complexity (very inefficient for large n).
  • Optimized (Prime Factorization): The time complexity is O(sqrt(n)) because we only need to check up to the square root of n for factors. Space complexity is O(1) since we use only a few variables.

Summary

The 2 Keys Keyboard problem challenges us to find the most efficient sequence of Copy All and Paste operations to reach exactly n 'A's. By recognizing the connection between the operations and the factorization of n, we reduce the problem to summing its prime factors. This insight leads to an elegant, efficient solution that is both simple to implement and optimal in performance.

Code Implementation

class Solution:
    def minSteps(self, n: int) -> int:
        ans = 0
        d = 2
        while n > 1:
            while n % d == 0:
                ans += d
                n //= d
            d += 1
        return ans
    
class Solution {
public:
    int minSteps(int n) {
        int ans = 0;
        for (int d = 2; n > 1; ++d) {
            while (n % d == 0) {
                ans += d;
                n /= d;
            }
        }
        return ans;
    }
};
    
class Solution {
    public int minSteps(int n) {
        int ans = 0;
        for (int d = 2; n > 1; ++d) {
            while (n % d == 0) {
                ans += d;
                n /= d;
            }
        }
        return ans;
    }
}
    
var minSteps = function(n) {
    let ans = 0;
    let d = 2;
    while (n > 1) {
        while (n % d === 0) {
            ans += d;
            n = Math.floor(n / d);
        }
        d++;
    }
    return ans;
};