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?
  1. A. 7 2
  2. B. 6 2
  3. C. 6 1
  4. 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

Exams that ask this topic