Clumsy Factorial Problem
Description
LeetCode Problem 1006.
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.
We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order.
- For example,
clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1.
However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11.
Given an integer n, return the clumsy factorial of n.
Example 1:
Input: n = 4
Output: 7
Explanation: 7 = 4 * 3 / 2 + 1
Example 2:
Input: n = 10
Output: 12
Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1
Constraints:
1 <= n <= 10^4
Solution
Approach: Stack Simulation
We cannot just evaluate left to right, because * and / bind tighter than + and -. The usual trick for evaluating such an expression is a stack of terms that will be added up at the end:
*and/change the last term: replace the top of the stack bytop * xortop / x.+pushesxas a new term, and-pushes-x.
The operators cycle *, /, +, -, so we keep an index op that goes 0, 1, 2, 3, 0, ... as we walk x from n - 1 down to 1. The answer is the sum of the stack.
The tricky part is the division. After a -, the top of the stack is negative (for n = 10, the term - 6 * 5 / 4 is stored as -30 / 4), and it must become -7, not -8: the division really applies to 6 * 5, and the minus comes after. So the division has to truncate toward zero. That is what / does in Java, C++, Go, and Math.trunc in JavaScript; in Python, // would round down to -8, so we use int(a / x) instead.
Complexity: O(n) time and O(n) extra space for the stack.
class Solution:
def clumsy(self, n: int) -> int:
stk = [n] # terms still to be added up; * and / work on the last one
op = 0 # 0: *, 1: /, 2: +, 3: -
for x in range(n - 1, 0, -1):
if op == 0:
stk.append(stk.pop() * x)
elif op == 1:
stk.append(int(stk.pop() / x)) # truncate toward zero: the term may be negative
elif op == 2:
stk.append(x)
else:
stk.append(-x)
op = (op + 1) % 4
return sum(stk)