VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-sprinkers-required-to-be-turned-on-to-water-the-plants/

⇱ Minimum Workers to Cover All Hours - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Workers to Cover All Hours

Last Updated : 5 Sep, 2025

Given an array arr[] of size n, where each element arr[i] denotes the range of working hours a person at position i can cover.

  • A person at index i can work and cover the time interval [i - arr[i], i + arr[i]].
  • If arr[i] = -1, the person is unavailable and cannot cover any time.

Find the minimum number of people required to cover the entire interval [0, n – 1]. If it is not possible, return -1.

Examples:

Input: arr[] = [1, 2, 1, 0]
Output: 1
Explanation: The person at index 1 can cover the interval [-1, 3]. After adjusting to valid bounds, this becomes [0, 3], which fully covers the entire working day 0 to n -1. Therefore, only 1 person is required to cover the whole day.

Input: arr[] = [0, 1, 0, -1]
Output: -1
Explanation: Person at index 0 covers [0, 0].
Person at index 1 covers [0, 2].
Person at index 2 covers [2, 2].
Since the last hour cannot be covered by any person, it is impossible to cover the full working day.

[Approach] Using Greedy and Sorting - O(n log(n)) Time and O(n) Space

The idea is to always pick the worker who extends coverage the farthest when the current coverage ends. The problem is to cover the full timeline [0 … n-1] using workers’ ranges. Each worker at index i can cover [i - arr[i], i + arr[i]]. We need the minimum number of workers so that all hours are covered without gaps. This reduces to a minimum interval covering problem.

How it works?

  • We need to cover the full timeline [0 … n-1] using the fewest intervals.
  • Each worker gives an interval [i - arr[i], i + arr[i]].
  • At each step, we track the current coverage (maxi).
  • The next chosen interval must start at or before maxi + 1.
  • If no such interval exists, coverage is impossible.
  • Among valid intervals, pick the one with the farthest right endpoint to maximize future coverage.

Output
1
Comment