2 Keys Keyboard — LeetCode 650 Python Solution
- Problem
- #650
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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: Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).
Example
- Input
- n = 3
- Output
- 3
- Explanation
- Initially, we have one character 'A'.
Python solution
class Solution:
def minSteps(self, n: int) -> int:
@cache
def dfs(n):
if n == 1:
return 0
i, ans = 2, n
while i * i <= n:
if n % i == 0:
ans = min(ans, dfs(n // i) + i)
i += 1
return ans
return dfs(n)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 650. 2 Keys Keyboard is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 650. 2 Keys Keyboard?
- LeetCode 650. 2 Keys Keyboard is rated Medium on LeetCode.
- What topics does LeetCode 650. 2 Keys Keyboard cover?
- LeetCode 650. 2 Keys Keyboard is tagged Math and Dynamic Programming on LeetCode.