Clumsy Factorial — LeetCode 1006 Python Solution
MediumStackMathSimulation
- Problem
- #1006
- Pattern
- Stack
- Reading time
- 3 min
- Source
- leetcode.com
The problem
The factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.
Example
- Input
- n = 4
- Output
- 7
- Explanation
- 7 = 4 * 3 / 2 + 1
Python solution
Python
class Solution:
def clumsy(self, n: int) -> int:
k = 0
stk = [n]
for x in range(n - 1, 0, -1):
if k == 0:
stk.append(stk.pop() * x)
elif k == 1:
stk.append(int(stk.pop() / x))
elif k == 2:
stk.append(x)
else:
stk.append(-x)
k = (k + 1) % 4
return sum(stk)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1006. Clumsy Factorial is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1006. Clumsy Factorial?
- LeetCode 1006. Clumsy Factorial is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1006. Clumsy Factorial?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1006. Clumsy Factorial?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1006. Clumsy Factorial cover?
- LeetCode 1006. Clumsy Factorial is tagged Stack, Math and Simulation on LeetCode.