Data Structures & AlgorithmsHard
The numbers 1, 2, 3, 4, 5 are pushed onto an initially empty stack in this order, and a pop may be performed whenever the stack is non-empty. How many DIFFERENT output sequences (order in which elements leave) are possible?
- A. 120
- B. 32
- C. 42
- D. 14
Correct answer: C. 42
Each output is a stack-permutation, and the count of distinct ones for n elements is the Catalan number C(n) = (2n)!/((n+1)!·n!). For n = 5 that gives 42, while the unrestricted 5! = 120 and the power-of-two count ignore the stack discipline.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is the minimum number of positive integers (each value at most 10, repetitions allowed in the array) needed so that EVERY integer…
- Given a sorted array, why is counting triplets with sum < T O(n²) rather than O(n³)?
- Floyd's cycle detection finds the slow and fast pointers meeting inside the loop. How is the START of the loop then found?
- In the greedy patching algorithm, the reachable range is [1..R] and the next sorted value x exceeds R+1. Why is R+1 the right patch?
- A monotonic deque for sliding-window maximum stores array INDICES instead of values. Why?
- When tracking a '' wildcard that may be '(', ')' or empty while scanning brackets, why is it enough to keep a range [lo, hi] of possible…