2 Keys Keyboard - Problem

Imagine you're working with a simple text editor that starts with a single character 'A' on the screen. This editor has a unique constraint - it only has two keys:

  • Copy All: Copies all characters currently on the screen to the clipboard (partial copying is not allowed)
  • Paste: Pastes whatever was last copied

Your goal is to find the minimum number of operations needed to get exactly n copies of the character 'A' on the screen.

Example: To get 3 A's:

  1. Start: A
  2. Copy All: A (clipboard now has 'A')
  3. Paste: AA
  4. Paste: AAA

Total: 3 operations

Input & Output

example_1.py β€” Simple case
$ Input: n = 3
β€Ί Output: 3
πŸ’‘ Note: Start with A. Copy All (1 op) β†’ clipboard has A. Paste (1 op) β†’ AA. Paste (1 op) β†’ AAA. Total: 3 operations. Prime factorization: 3 is prime, so answer is 3.
example_2.py β€” Composite number
$ Input: n = 9
β€Ί Output: 6
πŸ’‘ Note: 9 = 3 Γ— 3, so we need sum of prime factors = 3 + 3 = 6. Sequence: A β†’ Copy+Paste+Paste β†’ AAA β†’ Copy+Paste+Paste β†’ AAAAAAAAA (9 A's).
example_3.py β€” Edge case
$ Input: n = 1
β€Ί Output: 0
πŸ’‘ Note: We already have 1 A on the screen, so no operations needed.

Visualization

Tap to expand
Copy-Paste Factory (n=6 example)Production Line OptimizationAStart: 1 unitCOPYTemplate: AAAAfter Paste: 2 unitsCOPYTemplate: AAAAAAAAFinal: 6 unitsMathematical Insight6 = 2 Γ— 3 (prime factorization)β€’ Factor 2: Copy + Paste (2 operations) β†’ 1A becomes 2Aβ€’ Factor 3: Copy + 2Γ—Paste (3 operations) β†’ 2A becomes 6ATotal: 2 + 3 = 5 operations
Understanding the Visualization
1
Factory Setup
Start with 1 item on the production line
2
Create Template
Copy All creates a template of your current production
3
Scale Production
Paste adds one template's worth of items to your line
4
Optimize Strategy
Prime factorization tells us the optimal copy-paste sequence
Key Takeaway
🎯 Key Insight: The minimum operations equals the sum of prime factors because each prime factor represents the most efficient copy-paste sequence for that multiplication step.

Time & Space Complexity

Time Complexity
⏱️
O(√n)

We only need to check factors up to √n, as larger factors would have been found as quotients

n
2n
βœ“ Linear Growth
Space Complexity
O(1)

Only uses a few variables, no additional data structures needed

n
2n
βœ“ Linear Space

Constraints

  • 1 ≀ n ≀ 1000
  • n is a positive integer
  • Time limit: 1 second per test case
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 15
67.4K Views
Medium Frequency
~15 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