Knowledge Guide
HomeDSACompany Practice

medium 2 Keys Keyboard

Problem Statement

You're given a notepad that initially displays a single character 'A'. You have two actions available to perform on this notepad for each step:

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

Examples

Try it yourself

Try solving this question here:

✅ Solution 2 Keys Keyboard

Problem Statement

You're given a notepad that initially displays a single character 'A'. You have two actions available to perform on this notepad for each step:

  • Copy All: It allows you to copy everything on the screen.
  • Paste: You can paste the characters which are copied last time.

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

Examples

  • Example 1:

    • Input: n = 4
    • Expected Output: 4
    • Justification: Start with 'A', copy it (1 operation), and paste it(1 operations). Now, you have 'AA'. Copy it, and paste it. Total = 4 operations.
  • Example 2:

    • Input: n = 5
    • Expected Output: 5
    • Justification: Start with 'A', copy it, and paste it four times. Total = 5 operations.
  • Example 3:

    • Input: n = 9
    • Expected Output: 6
    • Justification: Start with 'A', copy and paste twice (3 operations) to get 'AAA'. Copy 'AAA' and paste it twice (3 operations) to get 'AAAAAAAAA'. Total = 6 operations.

Solution

To solve this problem, we'll focus on breaking down the target number n into its prime factors, because the minimum number of operations needed to achieve n 'A's on the screen can be thought of in terms of multiplying the counts of 'A's by repeatedly copying and pasting. This strategy works because copying and pasting a larger block of 'A's, which is a multiple of smaller blocks, mirrors the process of constructing a number by multiplying its factors. Thus, our approach will be to find the sum of the prime factors of n as this sum represents the minimum number of steps needed to get n 'A's on the screen.

This approach is effective because it leverages the mathematical property that any composite number can be expressed as a product of prime numbers, and the operations to achieve the target n can be seen as the process of building up to n through these prime multiplicands. Therefore, by analyzing n in terms of its prime components, we can efficiently determine the least number of steps required.

Step-by-step algorithm

  • Initialize totalOperations to 0, which will hold our final count of operations.
  • Iterate from i = 2 to n:
    • While n % i == 0 (meaning i is a factor of n):
      • Add i to totalOperations (representing the operation count needed to achieve i copies).
      • Divide n by i to reduce our problem size and reflect that we've accounted for this factor.
  • Return totalOperations as the answer.

Algorithm Walkthrough

Let's consider the input: n = 9.

  1. Initialize operations to 0. This variable tracks the total number of operations required.
  2. Start iterating i from 2 to n (inclusive).
    • For n = 9, start with i = 2.
  3. Check if n % i == 0 (if n is divisible by i without a remainder).
    • For i = 2, 9 % 2 != 0. So, move to the next i.
    • For i = 3, 9 % 3 == 0. This is true, so enter the while loop.
  4. Inside the while loop, add i to operations. For the first iteration, add 3 to operations.
  5. Divide n by i, setting n to n / i. For the first iteration, set n = 9 / 3 = 3.
  6. Check again if n % i == 0. Since n is now 3 and i is also 3, the condition is true.
    • Add i (3) to operations again. Now, operations = 6.
    • Divide n by i again, now n = 3 / 3 = 1.
  7. Since n is now 1, the loop for i = 3 finishes.
  8. There are no more divisors of n (now 1) greater than 1, so the outer loop terminates.
  9. The value of operations is now 6, which is the expected minimum number of operations to get the character 'A' exactly n times on the screen for n = 9.

Code

java
public class Solution {

  // Method to calculate the minimum operations required
  public int minOperations(int n) {
    int operations = 0; // Initialize the count of operations

    // Iterate over all numbers from 2 to n
    for (int i = 2; i <= n; i++) {
      // While n is divisible by the current number i, perform the following:
      while (n % i == 0) {
        operations += i; // Add the current divisor i to the operations count
        n /= i; // Divide n by i to reduce it
      }
    }

    return operations; // Return the total count of operations
  }

  // Main method to test the examples
  public static void main(String[] args) {
    Solution solution = new Solution();

    // Example 1
    System.out.println(solution.minOperations(4)); // Expected Output: 4

    // Example 2
    System.out.println(solution.minOperations(5)); // Expected Output: 5

    // Example 3
    System.out.println(solution.minOperations(9)); // Expected Output: 6
  }
}

Complexity Analysis

Time Complexity

The time complexity of the provided code is in the worst case, primarily because it iterates through all numbers up to n and performs division operations that, in the worst case, can be as costly as iterating up to the square root of n for each number.

Space Complexity

The space complexity is , as it uses a fixed amount of space regardless of input size.

🤖 Don't fully get this? Learn it with Claude

Stuck on 2 Keys Keyboard? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **2 Keys Keyboard** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **2 Keys Keyboard** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **2 Keys Keyboard**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **2 Keys Keyboard**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes