Data Structures & AlgorithmsVery hardProduct placement · Amazon/Microsoft
A min-stack keeps a second stack of running minimums. What is printed?
A min-stack keeps a second stack of running minimums. What is printed?
st, mn, out = [], [], []
for op in [8, "pop", 8, 8, "pop", 3, 5, 3]:
if op == "pop":
x = st.pop()
if x == mn[-1]: mn.pop()
else:
st.append(op)
if not mn or op <= mn[-1]: mn.append(op)
out.append(mn[-1] if mn else None)
print(out)- A. [8, 8, None, 8, 8, 3, 3, 3]
- B. [8, None, 8, 8, None, 3, 3, 3]
- C. [8, None, 8, 8, 3, 8, 3, 3]
- D. [8, None, 8, 8, 8, 3, 3, 3]
Correct answer: D. [8, None, 8, 8, 8, 3, 3, 3]
A value is pushed onto the min-stack when it is ≤ the current minimum; using < breaks when a duplicate minimum is popped. Output: [8, None, 8, 8, 8, 3, 3, 3].
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
- Reverse a singly linked list in groups of k (a final group shorter than k is left as it is). What is printed? python def revk(h, k): cnt…
- Print a matrix in spiral order (right, down, left, up, repeat). What is printed? python m = [[50, 81, 32, 23], [30, 61, 32, 23], [60, 51…
- A chained hash table stores n = 2,000 keys in m = 500 buckets with simple uniform hashing. What is the expected number of key comparisons…
- Bars of width 1 have heights [5, 5, 7, 8, 6, 5, 2, 8]. What is the area of the largest rectangle that fits under the histogram (computed…
- Product of all elements except self, using prefix and suffix products (no division). What is printed? python a = [2, 3, 3, 2, -1] n =…
- What does this loop-counting code print? (Python) python n, c = 16, 0 i = 1 while i < n: j = i while j < n: c += 1 j = 2 i += 1 print(c)