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?- A. True True
- B. False True
- C. True False
- 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
- Problem: People queue at a single counter; person i wants t[i] tickets, buys one per second and, if still needing more, goes to the back…
- Problem: Regroup a linked list so that all nodes at odd positions (1st, 3rd, …) come first, followed by the even positions, keeping…
- Problem: Rotate a linked list to the right by k places (k may exceed the length). python class Node: def init(self, v, nxt=None): self.v…
- Problem: Each rescue boat carries at most two people and at most limit kg. Find the minimum number of boats (greedy: pair the heaviest…
- Problem: Count how many query words are subsequences of a long log string, using per-letter position lists and binary search (instead of…
- Problem: A candy-crush style cleaner repeatedly deletes any k equal adjacent letters (cascading) until none remain. A stack of (letter…