Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: A min-stack supports push, pop, top and getMin in O(1) by storing (value, current minimum) pairs.
Problem: A min-stack supports push, pop, top and getMin in O(1) by storing (value, current minimum) pairs.
st, out = [], [] def push(x): st.append((x, min(x, st[-1][1]) if st else x)) def pop(): st.pop() def get_min(): return st[-1][1] for x in [5, 3, 7, 3, 8]: push(x) out.append(get_min()); pop(); pop(); out.append(get_min()); pop(); out.append(get_min()) print(out)What is printed?
- A. [3, 3, 5]
- B. [3, 3, 3]
- C. [3, 5, 5]
- D. [3, 7, 5]
Correct answer: B. [3, 3, 3]
Each entry remembers the minimum at the time it was pushed: (5,5), (3,3), (7,3), (3,3), (8,3). After popping 8 and 3 the top is (7,3) → 3; after popping 7 the top is (3,3) → 3. Duplicated minima (two 3s) are handled automatically.
More Coding Interview Problems questions
- Problem: Josephus problem: n people in a circle, every k-th person is eliminated; find the 1-based position of the survivor. python def…
- Problem: Count permutations of 1..n where, for every position i (1-based), the value is divisible by i or i is divisible by the value…
- Problem: Each candidate can be used at most ONCE and the list has duplicates; count the distinct combinations that sum to the target…
- Problem: Divide two integers without , / or %, truncating toward zero, using doubling (shifts). python def divide(a, b): neg = (a < 0) !=…
- Problem: Traverse a matrix along anti-diagonals, alternating direction (up-right first). python def diag(m): R, C = len(m), len(m[0]); out…
- Edge case: building a 3 × 3 grid with list multiplication. python grid = [[0] 3] 3 grid[0][0] = 1 print(grid) What is printed?