Data Structures & AlgorithmsHardTCS NQT · Infosys pattern

What is printed? (stack: check if a sequence of pops is possible after pushing 1..n in order)

What is printed? (stack: check if a sequence of pops is possible after pushing 1..n in order)
def valid(pushed, popped):
    st, j = [], 0
    for x in pushed:
        st.append(x)
        while st and j < len(popped) and st[-1] == popped[j]:
            st.pop(); j += 1
    return j == len(popped)
p = [1, 2, 3, 4, 5]
print(valid(p, [4, 5, 3, 2, 1]), valid(p, [4, 3, 5, 1, 2]), valid(p, [3, 2, 1, 5, 4]))
  1. A. True True True
  2. B. False False True
  3. C. True False True
  4. D. True False False

Correct answer: C. True False True

Simulate: push in order and pop greedily whenever the top matches the next expected value. In [4, 3, 5, 1, 2], after popping 4, 3, 5 the stack is [1, 2] with 2 on top, so 1 cannot come next. O(n).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic