Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Walk along buildings of given heights; climbing up by d needs d bricks or one ladder (going down is free). Return the furthest index reachable. Keep the ladders for the largest climbs with a min-heap.
Problem: Walk along buildings of given heights; climbing up by d needs d bricks or one ladder (going down is free). Return the furthest index reachable. Keep the ladders for the largest climbs with a min-heap.
import heapq
def furthest(h, bricks, ladders):
used = []
for i in range(len(h) - 1):
d = h[i + 1] - h[i]
if d > 0:
heapq.heappush(used, d)
if len(used) > ladders:
bricks -= heapq.heappop(used)
if bricks < 0: return i
return len(h) - 1
h = [3, 8, 6, 12, 13, 20, 18, 25]
print(furthest(h, 7, 2), furthest(h, 2, 1))What is printed?- A. 7 2
- B. 6 2
- C. 6 1
- D. 5 2
Correct answer: B. 6 2
The heap holds the climbs currently 'paid' by ladders; when it exceeds the ladder count, the smallest of them is paid with bricks instead. Climbs: 5, 6, 1, 7, 7. With 7 bricks and 2 ladders: 1 → bricks (6 left), then 7 forces the 5 onto bricks (1 left), then the last 7 forces the 6 onto bricks → −5 → stuck at index 6. With 2 bricks and 1 ladder: the second climb pushes 5 onto bricks → stuck at index 2. Using ladders greedily on the first climbs is wrong. O(n log L).
More Coding Interview Problems questions
- Problem: Find the smallest range [lo, hi] that contains at least one number from each of k sorted lists (min-heap of one pointer per list…
- Problem: Choose the root(s) that minimise the height of an unrooted tree. Repeatedly strip all current leaves; the last 1 or 2 nodes are…
- Problem: Count the strongly connected components of a directed graph with Kosaraju's algorithm (DFS finishing order, then DFS on the…
- Problem: Stones sit on grid points; a stone may be removed if another remaining stone shares its row or column. Maximum removable = stones…
- Problem: Build row k of Pascal's triangle (row 0 = [1]) by adding neighbouring entries of the previous row. python def pascalrow(k): row =…
- Problem: Count binary strings of length n with no two adjacent 1s, tracking how many valid strings end in 0 and in 1. python def no11(n)…