Skip to content
Problem 650 · LeetCode 650(opens in a new tab)

2 Keys Keyboard

MediumDynamic programming

A text editor shows a single letter A. You have two keys. Copy puts everything on the screen into the clipboard; you cannot copy part of it. Paste adds the clipboard to the end of the screen.

Given a number n, return the fewest key presses needed to have exactly n letters A on the screen.

Example 1

Input:  n = 12
Output: 7
Why:    copy, paste (2), copy, paste (4), copy, paste, paste (12)
2 more examples and the constraints

Example 2

Input:  n = 1
Output: 0
Why:    the screen already has one letter

Example 3

Input:  n = 7
Output: 7
Why:    7 is prime: copy once, paste 6 times

Constraints

  • 1 ≤ n ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DP over divisorsO(n²)
  2. Sum of prime factorsO(√n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 1,000Verdict
DP over divisorsO(n²)
Passes; a good way in
Sum of prime factorsO(√n)
Best; a few divisions

n = the number of letters wanted.

Edge cases to test

  • n = 1. Nothing to do: the answer is 0.
  • n is prime. 997 needs 997 moves; no shortcut exists.
  • Repeated factors. 12 = 2 · 2 · 3 counts the 2 twice: 7, not 5.
  • A square of a prime. 961 = 31 · 31: the loop must leave d · d ≤ n inclusive, or the second 31 is lost.

Common mistakes

  • Returning n − 1 or n for every n, forgetting that copying a bigger screen saves moves.
  • Counting each prime factor once instead of once per time it divides n.
  • Forgetting the prime left over after the trial-division loop.

How to talk through it

  1. 1Clarify. Does the first copy count as a move? Is n = 1 already done?
  2. 2Give the DP. The last copy happens at some divisor j; dp[n] = best dp[j] + n/j. Say it is O(n²).
  3. 3See the product. A round of k moves multiplies by k, and a + b ≤ a·b, so split rounds into primes.
  4. 4Code the factor sum. Trial division up to √n, then add any prime left.
  5. 5Test out loud. Run n = 1, a prime like 7, and 12 with its repeated 2.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?