Problem
Given an input of n
distinct characters, find a simple formula to determine the number of valid permutations (An
) that can be printed by processing the characters through a stack. A valid permutation is one where the output sequence can be generated using stack operations (push and pop).
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Catalan Number
We have already seen Catalan Numbers, and use its formula: $$ C_n = \frac{1}{n+1} \binom{2n}{n} = \frac{(2n)!}{(n+1)!n!} $$
- Understanding the Catalan Number:
- The nth Catalan number provides the count of different ways to correctly match parentheses, or considering stack operations, the number of valid sequences of push and pop operations.
- It reflects the number of valid permutations of
n
elements when pushed and popped from a stack without violating the stack order.
- Computational Steps:
- Compute the factorial values required for the Catalan formula.
- Use the formula to calculate the Catalan number for the given
n
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
because we only traverse the string once. - 🧺 Space complexity:
O(1)
because we only use a constant amount of additional space.