There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:
Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.
Example 1:
Input: n = 3 Output: 3 Explanation: Initially, we have one character 'A'. In step 1, we use Copy All operation. In step 2, we use Paste operation to get 'AA'. In step 3, we use Paste operation to get 'AAA'.
Example 2:
Input: n = 1 Output: 0
Constraints:
1 <= n <= 1000This approach involves using a dynamic programming array where dp[i] represents the minimum number of operations required to achieve exactly i 'A's on the screen. The idea is to divide the problem into subproblems and solve each subproblem once to build up a solution for the original problem. For each integer i, if it can be obtained from j by first copying all from j and pasting (i/j-1) times, then dp[i] can be updated as dp[j] + i/j steps.
This C solution initializes an array of size n+1 to track minimum steps for each possible number of 'A's up to n. We iterate over each possible number of 'A's, checking for each j (where 1 <= j < i) if i can be entirely divided by j. If so, update dp[i] using dp[j] plus the number of pastes needed to reach i from j.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2) due to the nested loops for divisor checking.
Space Complexity: O(n) to store the dynamic programming array.
The optimal strategy is based on a mathematical observation wherein the solution boils down to the prime factorization of n. Essentially, if you can find all factors of numbers up to n, the minimum operations needed are the sum of the prime factors of these numbers. Whenever you can make a sequence by repeating operations, using a simple Copy All and Paste enough times to reach a bigger number allows the number of operations to be minimized via multiplying smaller sequences.
This C solution employs a strategy of dividing n by its smallest divisor d (starting from 2) repeatedly, summing the divisor to count. This extracts all the prime factors and sums them for minimum operations.
C++
Java
Python
C#
JavaScript
Time Complexity: O(√n) as it iterates over possible factors up to the square root of n.
Space Complexity: O(1) with constant auxiliary space usage.
| Approach | Complexity |
|---|---|
| Dynamic Programming Solution | Time Complexity: O(n^2) due to the nested loops for divisor checking. |
| Mathematical Analysis with Prime Factors | Time Complexity: O(√n) as it iterates over possible factors up to the square root of n. |
2 Keys Keyboard - Leetcode 650 - Python • NeetCodeIO • 16,684 views views
Watch 9 more video solutions →Practice 2 Keys Keyboard with our built-in code editor and test cases.
Practice on FleetCode