2 Keys Keyboard - Problem

There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:

  • Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).
  • Paste: You can paste the characters which are copied last time.

Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.

Input & Output

Example 1 — Basic Case
$ Input: n = 3
Output: 3
💡 Note: Initially we have 1 'A'. Copy All (1 op) → clipboard has 'A', screen has 'A'. Paste (1 op) → screen has 'AA'. Paste (1 op) → screen has 'AAA'. Total: 3 operations.
Example 2 — Composite Number
$ Input: n = 9
Output: 6
💡 Note: Optimal path: Copy 1A → Paste to get 3A (3 ops), then Copy 3A → Paste to get 6A → Paste to get 9A (3 more ops). Total: 6 operations. This equals 3+3 (prime factors of 9 = 3²).
Example 3 — Prime Number
$ Input: n = 7
Output: 7
💡 Note: Since 7 is prime, we can only paste one by one: Copy 1A, then paste 6 times to get 7A. Total: 7 operations.

Constraints

  • 1 ≤ n ≤ 1000

Visualization

Tap to expand
2 Keys Keyboard: Copy-Paste to get n=6 charactersAStart (1A)AACopy+PasteAAAAAACopy+Paste×22 ops3 opsOperations Breakdown1A → Copy → Paste → 2A (2 ops)2A → Copy → Paste → Paste → 6A (3 ops)Prime factorization: 6 = 2×3, sum = 2+3 = 5Total: 5 operations (minimum possible)
Understanding the Visualization
1
Initial State
Start with 1 'A' on screen
2
Copy-Paste Strategy
Choose optimal sequence of copy and paste operations
3
Target Reached
Achieve exactly n 'A's with minimum operations
Key Takeaway
🎯 Key Insight: The minimum operations equals the sum of all prime factors of n
Asked in
Google 35 Microsoft 28 Amazon 22
78.5K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen