[
recursion
math
stack
simulation
]
Leetcode 1006. Clumsy Factorial
Problem statement
https://leetcode.com/problems/clumsy-factorial/
Solution
One possible solution is to notice some pattern and use recursion.
Let us f(x)
be clumsy factorial, but where the first term is taken with - sign. Then we can evaluate f(x)
recursively. Then to evaluate clumsy factorial we need to add twice the first term.
Complexity
It is O(n)
for time and space.
Code
class Solution:
def clumsy(self, n):
def f(x):
if x <= 4:
return [0, -1, -2, -6, -5][x]
else:
return -(x*(x-1)//(x-2)) + (x-3) + f(x-4)
return f(n) + 2*((n*(n-1))//(n-2)) if n > 4 else [0, 1, 2, 6, 7][n]