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 - Optimal Solution INPUT Notepad A Initial state Operations: Copy All Paste Target: n = 3 Get exactly 3 'A's with min operations Goal: "AAA" ALGORITHM STEPS 1 Start: 1 'A' Screen: "A" | Clipboard: empty 2 Copy All (Op #1) Screen: "A" | Clipboard: "A" 3 Paste (Op #2) Screen: "AA" | Clipboard: "A" 4 Paste (Op #3) Screen: "AAA" | Clipboard: "A" Prime Factorization Insight n=3 is prime, so min ops = 3 Formula: Sum of prime factors 3 = 3 (prime) --> ops = 3 A --> A --> AA --> AAA FINAL RESULT AAA Final Screen State Total Operations 3 Operation Breakdown 1. Copy All 2. Paste 3. Paste OK Output: 3 Key Insight: The minimum operations equals the sum of prime factors of n. For n=3 (prime), we need exactly 3 ops. For any prime p: 1 Copy + (p-1) Pastes = p operations. For composite n: recursively apply to factors. Example: n=6 = 2*3 --> ops = 2+3 = 5 (Copy, Paste, Copy, Paste, Paste) TutorialsPoint - 2 Keys Keyboard | Prime Factorization Approach
Asked in
Google 35 Microsoft 28 Amazon 22
78.6K 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