Data Structures & AlgorithmsHardProduct Company SDE · stack round
Problem: For each index of a = [4, 5, 2, 10, 8], find the index of the nearest element to its left that is strictly smaller (or -1). Run the monotone-stack code.
Problem: For each index of a = [4, 5, 2, 10, 8], find the index of the nearest element to its left that is strictly smaller (or -1). Run the monotone-stack code.
a = [4, 5, 2, 10, 8]
st = []
res = []
for i, x in enumerate(a):
while st and a[st[-1]] >= x:
st.pop()
res.append(st[-1] if st else -1)
st.append(i)
print(res)What is printed?- A. [-1, 0, -1, 2, 4]
- B. [-1, 0, -1, 2, 2]
- C. [-1, -1, -1, 2, 2]
- D. [-1, 0, 1, 2, 3]
Correct answer: B. [-1, 0, -1, 2, 2]
For 10 at index 3 the nearest smaller value is 2 at index 2, and for 8 it is again index 2. Using the nearest greater element instead gives a different list.
More Coding Interview Problems questions
- Problem: A directed flow network has source s = 0 and sink t = 3 with arcs and capacities: 0→1 (3), 0→2 (2), 1→2 (1), 1→3 (2), 2→3 (3)…
- Problem: A bottleneck path from vertex 0 to vertex 4 minimises the largest edge weight used. Using the undirected edges 0-1 (7), 1-2 (3)…
- Problem: A DAG has 4 vertices with edges 0→2 and 1→2 and 2→3 (vertices 0, 1 have no incoming arcs). How many distinct topological orders…
- Problem: In the undirected graph on vertices 0–4 with edges 0-1, 0-2, 1-2, 1-3, 2-3, 3-4, how many Hamiltonian paths exist (paths that…
- Problem: On a rooted tree (root 1) with children: 1: [2, 3], 2: [4, 5, 6], 3: [7], 5: [8, 9]. How many nodes have exactly 2 descendants…
- Problem: A binary tree is encoded in preorder with '#' for a missing child: "1,2,#,#,3,4,#,#,5,#,#". How many leaves (nodes with two…