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]))- A. True True True
- B. False False True
- C. True False True
- 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).
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 printed? (next greater element to the right, −1 if none) python a = [4, 5, 2, 25, 7, 8] res, st = [-1] len(a), [] for i in…
- Hash map counting: what is printed? (first element that repeats, scanning left to right) python def firstrepeat(a): seen = set() for x in…
- What is printed? (anagram check two ways) python from collections import Counter x, y = "listen", "enlists" print(sorted(x) == sorted(y)…
- Binary search: how many iterations does this loop run to find x = 23? python a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] lo, hi, it = 0…
- What is printed? (run-length decode then re-encode) python import re enc = "a3b1c12" dec = "".join(ch int(n) for ch, n in…
- What is printed? (move zeros to the end keeping order) python a = [0, 1, 0, 3, 12, 0, 5] w = 0 for r in range(len(a)): if a[r] != 0: a[w]…