All problems
0374HardArrayDynamic ProgrammingGreedy

Fewest Lamps to Light the Corridor

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1326Minimum Number of Taps to Open to Water a Garden

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A corridor runs from position 0 to position n. A lamp is fitted at every whole position from 0 through n, so there are n + 1 of them, and spread[i] says how far lamp i throws light: switched on, it lights the whole closed stretch from i - spread[i] to i + spread[i]. A lamp with a spread of 0 lights nothing at all, not even the point it hangs over.

Light spilling past position 0 or past position n is simply wasted.

Return the fewest lamps that can be switched on so that every point of the corridor from 0 to n is lit, or -1 if no combination of lamps manages it.

Examples

Example 1

Input
n = 6, spread = [0,3,0,0,0,2,0]
Output
2

Lamp 1 lights positions 0 through 4 once the spill below 0 is discarded, and lamp 5 lights positions 3 through 6. Together they cover the whole corridor with two lamps.

Example 2

Input
n = 8, spread = [4,0,0,0,4,0,0,0,4]
Output
1

Lamp 4 lights positions 0 through 8 on its own.

Example 3

Input
n = 4, spread = [0,0,0,0,0]
Output
-1

Every lamp has a spread of 0, so nothing is ever lit.

Example 4

Input
n = 5, spread = [2,0,0,0,0,2]
Output
-1

Lamp 0 reaches up to position 2 and lamp 5 reaches down to position 3, so the stretch between 2 and 3 stays dark whatever is switched on.

Constraints

  • 1 <= n <= 10^4
  • spread.length == n + 1
  • 0 <= spread[i] <= 100

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def min_taps(n: int, spread: list[int]) -> int:
Java
public int minTaps(int n, int[] spread)
September 7
Apply