2 Key keyboard problem in JavaScript

In this problem, we start with a notepad containing one character 'A' and need to reach exactly 'n' characters using only two operations: Copy All and Paste. The goal is to find the minimum number of steps required.

Problem Understanding

Given a notepad with one 'A', we can perform:

  • Copy All ? Copy all characters currently on the notepad
  • Paste ? Paste the previously copied characters

We need to find the minimum steps to get exactly 'n' A's on the notepad.

Example Walkthrough

For num = 3, the optimal sequence is:

  • Initial: 'A' (1 character)
  • Step 1: Copy All ? clipboard has 'A'
  • Step 2: Paste ? notepad has 'AA' (2 characters)
  • Step 3: Paste ? notepad has 'AAA' (3 characters)

Total steps: 3

Solution Approach

The key insight is that this problem reduces to finding the prime factorization of the target number. Each factor represents a "copy + multiple pastes" sequence.

const num = 3;

const minimumSteps = (num = 1) => {
    let [curr, copy, steps] = [1, 0, 0];
    
    while(curr != num) {
        if((copy 

3

Alternative Solution Using Prime Factorization

const minimumStepsOptimized = (n) => {
    if (n  1) {
        steps += n;
    }
    
    return steps;
};

console.log(minimumStepsOptimized(3));
console.log(minimumStepsOptimized(9));
console.log(minimumStepsOptimized(6));
3
6
5

How It Works

The algorithm tracks three variables:

  • curr ? Current number of A's on notepad
  • copy ? Number of A's in clipboard
  • steps ? Total operations performed

The condition (num - curr) % curr == 0 determines when it's optimal to copy instead of paste, ensuring we can reach the target with minimum steps.

Conclusion

This problem demonstrates dynamic programming concepts where we choose between copy and paste operations. The minimum steps equal the sum of prime factors of the target number.

Updated on: 2026-03-15T23:19:00+05:30

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements