Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Parcels 1..5 are pushed onto a loading stack in that order (pops may happen at any time). Decide whether a given pop order is achievable by simulating.

Problem: Parcels 1..5 are pushed onto a loading stack in that order (pops may happen at any time). Decide whether a given pop order is achievable by simulating.
def valid_seq(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)
print(valid_seq([1, 2, 3, 4, 5], [2, 4, 5, 3, 1]), valid_seq([1, 2, 3, 4, 5], [3, 1, 2, 5, 4]))
What is printed?
  1. A. True True
  2. B. False True
  3. C. True False
  4. D. False False

Correct answer: C. True False

Greedy simulation: push the next value and pop whenever the top equals the next required pop. Order 2, 4, 5, 3, 1 works (push 1, 2, pop 2; push 3, 4, pop 4; push 5, pop 5, then 3, 1). For 3, 1, 2, 5, 4: after popping 3 the top is 2, but 1 is required and is buried below it → impossible. O(n).

More Coding Interview Problems questions

Exams that ask this topic