Data Structures & AlgorithmsVery hardProduct Company SDE · interval covering OA
Problem: Minimum number of taps needed to water a garden of length 5 is found from tap i covering [i - ri, i + ri]. Here n = 5 and r = [3, 4, 1, 1, 0, 0] for taps 0..5. Run the greedy code. What is printed?
Problem: Minimum number of taps needed to water a garden of length 5 is found from tap i covering [i - r_i, i + r_i]. Here n = 5 and r = [3, 4, 1, 1, 0, 0] for taps 0..5. Run the greedy code. What is printed?
r = [3, 4, 1, 1, 0, 0]
n = 5
reach = [0] * (n + 1)
for i, x in enumerate(r):
L = max(0, i - x)
R = min(n, i + x)
for p in range(L, R + 1):
reach[p] = max(reach[p], R)
cur = best = 0
cnt = 0
end = 0
reach_end = 0
i = 0
while end < n:
while i <= n and i <= end:
reach_end = max(reach_end, reach[i])
i += 1
if reach_end == end:
cnt = -1
break
end = reach_end
cnt += 1
print(cnt)What is printed?- A. 2
- B. 3
- C. 1
- D. 5
Correct answer: C. 1
Tap 1 covers [0, 5] alone with radius 4 because it reaches the whole garden, so one tap suffices. The interval-jump greedy extends the covered end in one step here.
More Coding Interview Problems questions
- Problem: A stone game: piles [5, 3, 4, 5] lie in a row, and players alternately take a pile from either end. The first player wants to…
- Problem: Prim's algorithm starts at vertex 0 on the undirected weighted graph with edges 0-1 (6), 0-3 (2), 1-2 (3), 1-3 (8), 1-4 (5), 2-4…
- Problem: A directed graph on vertices 0–5 has arcs 0→1, 1→2, 2→0, 2→3, 3→4, 4→3, 4→5. Its strongly connected components are computed. How…
- Problem: The number of spanning trees of the complete graph K4 (4 labelled vertices, every pair joined by an edge) is what value?…
- Problem: A graph on vertices 0–6 has edges 0-1, 0-2, 1-3, 2-3, 3-4, 4-5, 5-6, 4-6. Count the bridges (edges whose removal increases the…
- Problem: Maximum bipartite matching is computed for left side {A, B, C, D} and right side {1, 2, 3, 4} with allowed pairs: A–1, A–2, B–2…