Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Walk along buildings; climbing up by d costs d bricks or one ladder (going down is free). Use ladders on the largest climbs (a min-heap of size = ladders). How far (index) can you get?
Problem: Walk along buildings; climbing up by d costs d bricks or one ladder (going down is free). Use ladders on the largest climbs (a min-heap of size = ladders). How far (index) can you get?
import heapq
def furthest(h, bricks, ladders):
heap = []
for i in range(len(h) - 1):
d = h[i+1] - h[i]
if d > 0:
heapq.heappush(heap, d)
if len(heap) > ladders:
bricks -= heapq.heappop(heap)
if bricks < 0: return i
return len(h) - 1
print(furthest([3, 8, 4, 10, 11, 6, 12, 20], 6, 2))What is printed?- A. 7
- B. 6
- C. 5
- D. 2
Correct answer: B. 6
Climbs are 5, 6, 1, 6, 8. Ladders stay on the two largest so far: the climb 1 is paid with bricks (5 left), the next 6 pushes the 5 onto bricks (0 left), and the final 8 forces a 6 onto bricks, which runs out, so you stop at index 6. Returning i + 1 gives 7, spending ladders on the first climbs gives 5, and forgetting the ladders altogether stops at index 2.
More Coding Interview Problems questions
- Problem: Return the k pairs (u from a, v from b) with the smallest sums, using a heap seeded with (a[i], b[0]). python import heapq def…
- Problem: Median of two sorted arrays in O(log(min(m, n))) by binary searching the partition of the shorter array. python def median(a, b)…
- Problem: Find the k-th positive integer missing from a strictly increasing array, by binary search on 'missing before index i' = a[i] − (i…
- Problem: Find the area of the largest square of 1s in a binary matrix. python def square(m): R, C = len(m), len(m[0]); dp = [[0] (C + 1)…
- Problem: Length of the longest common CONTIGUOUS subarray of two arrays (DP on suffix matches). python def common(a, b): dp = [[0] (len(b)…
- Problem: A knight makes k uniformly random moves (8 directions) on an n × n board; once it leaves the board it stays off. What is the…