Data Structures & AlgorithmsHardGoldman Sachs OA · LeetCode medium-hard
Problem: A ramp is a pair i < j with a[i] ≤ a[j]; its width is j − i. Find the maximum width using a decreasing stack of candidate left ends.
Problem: A ramp is a pair i < j with a[i] ≤ a[j]; its width is j − i. Find the maximum width using a decreasing stack of candidate left ends.
def ramp(a):
st = []
for i, x in enumerate(a):
if not st or a[st[-1]] > x: st.append(i)
best = 0
for j in range(len(a) - 1, -1, -1):
while st and a[st[-1]] <= a[j]:
best = max(best, j - st.pop())
return best
print(ramp([5, 2, 7, 1, 3, 4, 2, 6]))What is printed?- A. 6
- B. 4
- C. 5
- D. 7
Correct answer: D. 7
Only prefix minima (5, 2, 1 at indices 0, 1, 3) can be optimal left ends. Scanning from the right, a[7] = 6 pops 1, 2 and 5 in turn, and the last pop gives 7 − 0 = 7: the first and last elements already form a ramp. Pairing with the global minimum only gives width 4.
More Coding Interview Problems questions
- Problem: Return the k most frequent words, ties broken alphabetically. python from collections import Counter def topk(words, k): c =…
- Design a set supporting insert, delete and getRandom (uniform) all in O(1) average time. Which design works?
- Problem: Rotate a linked list to the right by k places. python class N: def init(s, v, nx=None): s.v, s.nx = v, nx def rotate(h, k): n, t…
- Problem: Partition a linked list so that all nodes with values < x come before nodes ≥ x, preserving relative order within each part…
- List A has a nodes before it joins a shared tail of c nodes; list B has b nodes before the same tail, with a ≠ b. Pointer p walks A and…
- Problem: Move the coins of a binary tree so every node has exactly one coin; a move passes one coin along one edge. Count the minimum…