You have a text editor with two special keys:
"A"
) which appends the character ‘A’ to the current text."Ctrl-V"
) which pastes the current clipboard content.Initially, you have n
‘A’s written on the clipboard, and you can only perform two operations:
Given n
, the goal is to find the minimum number of operations needed to get exactly n
‘A’s in the text.
The problem boils down to dividing the task into finding the smallest number of steps required to reach n
‘A’s starting with one ‘A’. This can be approached as follows:
Define dp[i]
as the minimum number of operations required to get i
‘A’s. Initially, we have:
dp[1] = 0
since one ‘A’ is our starting point.For every value of i
from 2 to n
:
j
where j
is a factor of i
(i % j == 0
).j
is a factor of i
, then paste the content (i/j
times) requiring i/j
operations after copying j
length text which also requires j
operations. Therefore, it takes dp[j] + (i / j)
operations in total to achieve i
copies.public class TwoKeysKeyboard {
public int minSteps(int n) {
// Edge case: since 1 'A' requires 0 operations.
if (n == 1) return 0;
// Define the dp array where dp[i] will store the min operations to get i 'A's.
int[] dp = new int[n + 1];
// Start with 0 operations needed for 1 'A' (base case)
dp[1] = 0;
// Fill dp array from 2 to n
for (int i = 2; i <= n; i++) {
dp[i] = i; // Start with the maximum which is all 'A' operations
for (int j = i - 1; j > 0; j--) {
if (i % j == 0) { // If divisible, we can copy paste from j
dp[i] = dp[j] + (i / j);
break;
}
}
}
return dp[n];
}
public static void main(String[] args) {
TwoKeysKeyboard solution = new TwoKeysKeyboard();
int n = 9; // Example
System.out.println("Minimum steps to get " + n + " 'A's: " + solution.minSteps(n));
}
}
\(j\)
of any i
can be done up until (\sqrt{n}).This approach is efficient and feasible for typical input sizes within constraint limits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?