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:
- Copy All: It allows you to
copy everythingon the screen. - Paste: You can
pastethe characters which arecopiedlast 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 (
1operation), and paste it(1operations). Now, you have 'AA'. Copy it, and paste it. Total =4operations.
- Input:
-
Example 2:
- Input:
n = 5 - Expected Output:
5 - Justification: Start with 'A', copy it, and paste it four times. Total =
5operations.
- Input:
-
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 =
6operations.
- Input:
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 everythingon the screen. - Paste: You can
pastethe characters which arecopiedlast 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 (
1operation), and paste it(1operations). Now, you have 'AA'. Copy it, and paste it. Total =4operations.
- Input:
-
Example 2:
- Input:
n = 5 - Expected Output:
5 - Justification: Start with 'A', copy it, and paste it four times. Total =
5operations.
- Input:
-
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 =
6operations.
- Input:
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
totalOperationsto 0, which will hold our final count of operations. - Iterate from
i = 2ton:- While
n % i == 0(meaningiis a factor ofn):- Add
itototalOperations(representing the operation count needed to achieveicopies). - Divide
nbyito reduce our problem size and reflect that we've accounted for this factor.
- Add
- While
- Return
totalOperationsas the answer.
Algorithm Walkthrough
Let's consider the input: n = 9.
- Initialize
operationsto 0. This variable tracks the total number of operations required. - Start iterating
ifrom 2 ton(inclusive).- For
n = 9, start withi = 2.
- For
- Check if
n % i == 0(ifnis divisible byiwithout a remainder).- For
i = 2,9 % 2 != 0. So, move to the nexti. - For
i = 3,9 % 3 == 0. This is true, so enter the while loop.
- For
- Inside the while loop, add
itooperations. For the first iteration, add 3 tooperations. - Divide
nbyi, settingnton / i. For the first iteration, setn = 9 / 3 = 3. - Check again if
n % i == 0. Sincenis now 3 andiis also 3, the condition is true.- Add
i(3) tooperationsagain. Now,operations = 6. - Divide
nbyiagain, nown = 3 / 3 = 1.
- Add
- Since
nis now 1, the loop fori = 3finishes. - There are no more divisors of
n(now 1) greater than 1, so the outer loop terminates. - The value of
operationsis now 6, which is the expected minimum number of operations to get the character 'A' exactlyntimes on the screen forn = 9.
Code
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 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
🤖 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.
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.
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.
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.
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.