#650
2 Keys Keyboard
MediumMathDynamic ProgrammingFactorizationDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the idea of factorization. Instead of simulating every operation, we can find the minimum operations by considering how many times we can copy and paste based on the factors of n.
⚙️
Algorithm
4 steps- 1Step 1: Initialize operations to 0.
- 2Step 2: For each integer i from 2 to n, check if i is a factor of n.
- 3Step 3: If it is, add i to operations and divide n by i.
- 4Step 4: Repeat until n becomes 1.
solution.py10 lines
1def minOperations(n):
2 operations = 0
3 i = 2
4 while n > 1:
5 if n % i == 0:
6 operations += i
7 n //= i
8 else:
9 i += 1
10 return operationsℹ
Complexity note: The time complexity is O(n) because we iterate through potential factors up to n, and for each factor, we may divide n multiple times.
- 1Understanding the relationship between operations and factors of n is crucial.
- 2Each operation can be viewed as a way to build up to n using its factors.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.