New update is available. Click here to update.

Last Updated: 12 Nov, 2020

Hard

```
Can you solve the problem in O(N) time?
```

```
The first line contains a single integer T representing the number of test cases.
The first line of each test case will contain the integer N.
The second and the last line of each test case will contain N single space-separated integers representing the elements of the array βrangesβ.
```

```
For each test case, print a single integer representing the value of the minimum number of taps needed to open by the gardener to fill the whole garden.
```

```
You do not need to print anything, it has already been taken care of. Just implement the given function.
```

```
1 <= T <= 10
1 <= N <= 10^4
0 <= ranges[i] <= 100
Time Limit: 1 sec
```

Approaches

- The idea to approach the problem is to convert the Ranges array into a list of intervals and sort them.
- As we need to choose minimum taps so at first we will find the farthest tap which we will choose so that it will cover the 0th coordinate and after choosing this coordinate we will update the leftmost coordinate with the right of the current chosen tap. This will act as the left boundary for the remaining taps to cover. Also increment the tap count to be returned.
- Now we repeat the above 2nd step until we cover all the possible coordinates(when we reach a tap which will cover a range more than equal to the last coordinate of the garden) or if there is no possible tap left that can cover the leftmost updated coordinate.

- Initialize a variable
**ans**= 1. - In this approach we will store the maximum range(rightmost index) that can be reached from the given index. For this we will create new array
**jumps**and initialize it with -1 this will indicate there is no tap that can reach the given coordinate. Now we will traverse the**ranges**array and for each element,- min = maximum of 0 and i - ranges[i].
**max = minimum of n and i + ranges[i].**- jumps[min] = maximum of jumps[min] and max.

- min = maximum of 0 and i - ranges[i].
- If jumps[0] = -1 this indicates that there is no tap that can cover the first coordinate of the garden and hence return -1.
- Initialize a variable
**cur**to jumps[0] to indicate the rightmost coordinate that is covered by selecting one tap. Also initialize two more variables**i**and**next**with 0. - While cur < n, the ground is not covered till the last coordinate n.
- While i < cur,
- update next = maximum of next and jumps[i]
- increase i by 1.

- If the next is same as cur, return -1. This indicates that we have covered all the taps and we can not water all the coordinates.

- While i < cur,
- Update cur with next and increment the
**ans**. - Return
**ans.**