Maximum number of characters using keystrokes A, CtrlA, CtrlC and CtrlV
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
This classic optimization problem asks for the maximum number of A characters that can appear on screen after exactly N keystrokes, where the only allowed actions are A, Ctrl+A, Ctrl+C, and Ctrl+V. The key insight is that once N gets large enough, repeatedly typing A is no longer optimal and a copy-paste phase wins.
Why Greedy Intuition Is Not Enough
At first, typing A every time seems reasonable.
For small values of N, it is optimal:
- '
N = 1gives1' - '
N = 2gives2' - '
N = 3gives3' - '
N = 4gives4' - '
N = 5gives5' - '
N = 6gives6'
But at N = 7, a better plan appears:
AAACtrl+ACtrl+CCtrl+VCtrl+V
That produces 9 characters on screen, not 7. The reason is that after copying a block, each paste adds the entire copied block rather than a single character.
Dynamic Programming Formulation
Let dp[n] be the maximum number of characters possible with exactly n keystrokes.
There are two broad choices:
- press
Aand add one character - at some earlier point, perform
Ctrl+A,Ctrl+C, then use the remaining steps forCtrl+V
If you stop at step b to prepare the clipboard, then:
- steps
1..bproducedp[b]characters - step
b+1isCtrl+A - step
b+2isCtrl+C - the remaining
n - b - 2steps are pastes
That means the total becomes:
dp[b] * (n - b - 1)
The extra 1 comes from the original copied screen plus all pastes.
So the recurrence is:
A Simple Python Implementation
This prints the optimal answer for each step count. The algorithm is O(n^2), which is usually fine because interview and puzzle versions of the problem use modest values of N.
How to Think About the Best Breakpoint
The only interesting question is when to stop typing and switch to copy-paste. Every copy cycle consumes two setup keystrokes, so switching too early is wasteful. Switching too late misses the multiplication effect.
Dynamic programming works because it tests every possible breakpoint and remembers the best result for smaller step counts. You do not need a fragile rule like “always switch after four As.” The best breakpoint depends on N.
Common Pitfalls
- Forgetting that
Ctrl+AandCtrl+Ceach cost a keystroke and must be counted. - Assuming the best answer for
N = 7is8; the optimal result is9. - Writing a recurrence that counts only pastes and forgets the already copied screen content.
- Using a greedy shortcut without checking all possible breakpoints.
- Confusing “maximum after at most
Nkeystrokes” with “maximum after exactlyNkeystrokes.”
Summary
- For small
N, pressingArepeatedly is optimal. - After a threshold, copy-paste beats direct typing.
- Dynamic programming is the standard way to solve the problem correctly.
- The recurrence depends on choosing the best breakpoint before
Ctrl+AandCtrl+C. - A simple
O(n^2)solution is usually enough for this problem.

