Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Design a stack that returns its minimum in O(1). The implementation below stores pairs.
Problem: Design a stack that returns its minimum in O(1). The implementation below stores pairs.
st = []
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, 2]:
push(x)
pop(); a = get_min()
pop(); pop(); c = get_min()
print(a, c)What is printed?- A. 2 5
- B. 3 5
- C. 3 3
- D. 2 3
Correct answer: C. 3 3
Each entry remembers the minimum at the time it was pushed: (5,5), (3,3), (7,3), (3,3), (2,2). One pop leaves (3,3) on top → 3. Two more pops remove (3,3) and (7,3), leaving the first (3,3) → 3 again. Keeping only a single 'current minimum' variable would lose the old minimum after popping. Every operation is O(1).
More Coding Interview Problems questions
- Problem: Return the first index whose value is ≥ x in a sorted array (n if none). cpp int lowerBound(vector<int>& a, int x) { int lo = 0…
- Problem: Count how many times a value occurs in a sorted array in O(log n). python from bisect import bisectleft, bisectright a = [2, 4…
- Problem: Search a target in a sorted array of distinct values that has been rotated at an unknown pivot. python def search(a, t): lo, hi =…
- Problem: Find the minimum of a rotated sorted array of distinct values. python def findmin(a): lo, hi = 0, len(a) - 1 while lo < hi: mid =…
- Problem: Packages with weights w (in order) must ship within D days; each day the ship carries a contiguous prefix of the remaining…
- Problem: A courier eats through n ≤ 10⁵ piles of parcels, pile sizes up to 10⁹, at speed k per hour (a pile smaller than k still takes a…