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

Exams that ask this topic