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.

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 ofn.

Examples

Example 1

1
2
3
Input: n = 4
Output: 7
Explanation: 7 = 4 * 3 / 2 + 1

Example 2

1
2
3
Input: n = 10
Output: 12
Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1

Constraints

  • 1 <= n <= 10^4

Solution

Method 1 – Stack Simulation

Intuition

Simulate the clumsy factorial by rotating through the operations (*, //, +, -) and using a stack to handle operator precedence. This approach mimics the order of operations and ensures correct calculation for each step.

Approach

  1. Initialize a stack with n.
  2. For each number from n-1 down to 1, apply the next operation in the sequence (*, //, +, -).
  3. For *, //, operate on the top of the stack. For +, push the number. For -, push -number.
  4. At the end, sum the stack for the result.

Complexity

  • ⏰ Time complexity: O(n), because we process each number from n down to 1 exactly once, and each stack operation is O(1).
  • 🧺 Space complexity: O(n), since the stack can grow up to size n in the worst case (when all operations are + or -).

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
public:
    int clumsy(int n) {
        vector<int> stk{n};
        int op = 0;
        for (int i = n - 1; i > 0; --i, ++op) {
            if (op % 4 == 0) stk.back() *= i;
            else if (op % 4 == 1) stk.back() /= i;
            else if (op % 4 == 2) stk.push_back(i);
            else stk.push_back(-i);
        }
        return accumulate(stk.begin(), stk.end(), 0);
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
type Solution struct{}
func (Solution) Clumsy(n int) int {
    stk := []int{n}
    n--
    op := 0
    for n > 0 {
        switch op % 4 {
        case 0:
            stk[len(stk)-1] *= n
        case 1:
            stk[len(stk)-1] /= n
        case 2:
            stk = append(stk, n)
        default:
            stk = append(stk, -n)
        }
        n--
        op++
    }
    ans := 0
    for _, v := range stk {
        ans += v
    }
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int clumsy(int n) {
        Stack<Integer> stk = new Stack<>();
        stk.push(n);
        n--;
        int op = 0;
        while (n > 0) {
            if (op % 4 == 0) stk.push(stk.pop() * n);
            else if (op % 4 == 1) stk.push(stk.pop() / n);
            else if (op % 4 == 2) stk.push(n);
            else stk.push(-n);
            n--;
            op++;
        }
        int ans = 0;
        while (!stk.isEmpty()) ans += stk.pop();
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
    fun clumsy(n: Int): Int {
        val stk = mutableListOf(n)
        var num = n - 1
        var op = 0
        while (num > 0) {
            when (op % 4) {
                0 -> stk[stk.lastIndex] = stk.last() * num
                1 -> stk[stk.lastIndex] = stk.last() / num
                2 -> stk.add(num)
                else -> stk.add(-num)
            }
            num--
            op++
        }
        return stk.sum()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def clumsy(self, n: int) -> int:
        ops = ['*', '//', '+', '-']
        stack = [n]
        n -= 1
        idx = 0
        while n > 0:
            op = ops[idx % 4]
            if op == '*':
                stack[-1] *= n
            elif op == '//':
                stack[-1] = int(stack[-1] / n)
            elif op == '+':
                stack.append(n)
            else:
                stack.append(-n)
            n -= 1
            idx += 1
        return sum(stack)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
impl Solution {
    pub fn clumsy(n: i32) -> i32 {
        let mut stk = vec![n];
        let mut num = n - 1;
        let mut op = 0;
        while num > 0 {
            match op % 4 {
                0 => *stk.last_mut().unwrap() *= num,
                1 => *stk.last_mut().unwrap() /= num,
                2 => stk.push(num),
                _ => stk.push(-num),
            }
            num -= 1;
            op += 1;
        }
        stk.iter().sum()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  clumsy(n: number): number {
    const stk: number[] = [n];
    n--;
    let op = 0;
    while (n > 0) {
      if (op % 4 === 0) stk[stk.length - 1] *= n;
      else if (op % 4 === 1) stk[stk.length - 1] = Math.trunc(stk[stk.length - 1] / n);
      else if (op % 4 === 2) stk.push(n);
      else stk.push(-n);
      n--;
      op++;
    }
    return stk.reduce((a, b) => a + b, 0);
  }
}