#1006
Clumsy Factorial
MediumMathStackSimulationStackSimulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a stack to manage the operations efficiently, allowing us to handle multiplication and division first, followed by addition and subtraction. This approach reduces unnecessary calculations and simplifies the process.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a stack and a variable to hold the current result.
- 2Step 2: Loop from n down to 1, applying operations based on the current operation index.
- 3Step 3: Push the result onto the stack for addition and subtraction, and calculate directly for multiplication and division.
solution.py16 lines
1def clumsy(n):
2 stack = []
3 current = n
4 op = 0
5 while current > 0:
6 if op == 0: # Multiply
7 stack.append(current if not stack else stack.pop() * current)
8 elif op == 1: # Divide
9 stack.append(stack.pop() // current)
10 elif op == 2: # Add
11 stack.append(current)
12 elif op == 3: # Subtract
13 stack.append(-current)
14 current -= 1
15 op = (op + 1) % 4
16 return sum(stack)ℹ
Complexity note: The time complexity is O(n) since we process each number once, and the space complexity is O(n) due to the stack used to store intermediate results.
- 1Understanding the order of operations is crucial.
- 2Using a stack can simplify handling multiple operations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.