2 Keys Keyboard (LeetCode 650): Solution and Explanation

Medium
Math
Dynamic Programming

A notepad starts with one A. Each step is either Copy All or Paste the last copy. Given n, return the fewest steps that leave exactly n A's on the screen.

Intuition

Look at the last Copy All before the screen reaches n. Say the screen had j A's at that moment. From then on, every Paste adds exactly j, so n must be a multiple of j, and the final stretch costs 1 copy plus n/j - 1 pastes, which is n/j steps in total.

Getting to j A's in the first place is the same problem with a smaller target. That gives the recurrence dp[i] = dp[j] + i/j, minimized over the divisors j of i, with dp[1] = 0. If i has no divisor besides 1, the only option is to copy the single A and paste i - 1 times, so dp[i] = i.

Which divisor is best? Doing a factor a*b as one round costs a*b, while doing it as two rounds (multiply by a, then by b) costs a + b. For a, b >= 2, a + b <= a*b, so splitting never hurts. That means the largest proper divisor, which leaves the smallest last factor, is always a best choice, and the scan can stop at the first divisor found from i/2 downward.

Unrolling this all the way, the screen is multiplied by one prime at a time, and the answer is the sum of the prime factors of n counted with multiplicity.

Approach: DP over the largest divisor

  1. Create dp of size n + 1 with dp[1] = 0.
  2. For each i from 2 to n, set dp[i] = i (the prime case).
  3. Scan j from i // 2 down to 2. At the first j that divides i, set dp[i] = dp[j] + i // j and stop.
  4. Return dp[n].

Step-by-step example

n = 12
  1. dp[1] = 0. dp[2] = 2 and dp[3] = 3, since both are prime.
  2. dp[4]: largest divisor 2, so dp[2] + 4/2 = 2 + 2 = 4.
  3. dp[6]: largest divisor 3, so dp[3] + 2 = 5.
  4. dp[12]: largest divisor 6, so dp[6] + 12/6 = 5 + 2 = 7.
  5. The screen grows 1 → 3 → 6 → 12: copy, paste, paste (3), copy, paste (6), copy, paste (12). That is 7 steps, and 2 + 2 + 3 = 7 is the sum of the prime factors of 12.

Code: Python, Java, C++

1class Solution:
2    def minSteps(self, n: int) -> int:
3        dp = [0] * (n + 1)
4        for i in range(2, n + 1):
5            dp[i] = i
6            for j in range(i // 2, 1, -1):
7                if i % j == 0:
8                    dp[i] = dp[j] + i // j
9                    break
10        return dp[n]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2) worst case

Each i scans down from i/2 until it finds a divisor; for primes that is about i/2 checks. For n <= 1000 this is well under a million operations.

Space

O(n)

The dp array holds one value per length up to n.

Other approaches

Prime factor sum (time O(sqrt n) with early stop, O(n) as usually written, space O(1))

Divide n by every factor d starting at 2 while d divides it, adding d to the answer each time. This is the closed form of the DP and needs no array.

BFS over (screen, clipboard) states (time O(n^2), space O(n^2))

Treat each pair of screen length and clipboard length as a node with edges for Copy All and Paste, and run BFS from (1, 0). It works but explores many states the math rules out.

Common mistakes

  • Returning 1 for n = 1. The screen already has one A, so the answer is 0.
  • Forgetting that the first operation must be Copy All. Paste with an empty clipboard does nothing, which is why a prime p costs p, not p - 1.
  • Counting n/j - 1 instead of n/j for the final stretch. The Copy All itself is a step.
  • Assuming fewer copies is always better. For 8, copying once and pasting 7 times costs 8, while doubling three times costs 6.

Frequently asked questions

Why is the largest divisor always optimal?

Any factor a*b with a, b >= 2 costs a*b in one round but only a + b in two rounds, and a + b <= a*b. So the best plan multiplies by primes, and the largest proper divisor leaves the smallest prime as the last step.

What does the answer look like for a prime n?

It is n itself: one Copy All followed by n - 1 pastes, since no other length divides n.

Is there an O(1) space solution?

Yes. Repeatedly divide n by its smallest factor and add that factor to the answer. The DP and this loop compute the same sum of prime factors.