Ctrl K

How Long the Light Stayed On

Easy
A hallway lamp has a motion sensor. When the sensor fires at second t, the lamp stays on for exactly hold seconds, from t through t + hold - 1 inclusive. If the sensor fires again while the lamp is still on, the timer restarts: the lamp now goes off hold seconds after the new trigger. You are given a non-decreasing list triggers of the seconds at which the sensor fired, and the number hold. Return the total number of seconds the lamp was on.
Example 1
triggers=[2, 3, 10], hold=3 → 7

The trigger at 2 turns the light on for seconds 2–4, but the one at 3 restarts the timer, so it stays on through second 5: seconds 2–5. Then seconds 10–12. That is 4 + 3 = 7.

Example 2
triggers=[0, 5], hold=5 → 10

The second trigger lands exactly when the light would have gone off: seconds 0–9, 10 in total.

Example 3
triggers=[4, 4], hold=2 → 2

Two triggers in the same second add nothing: the light is on for seconds 4 and 5.

Constraints
  • 1 ≤ len(triggers) ≤ 10⁴
  • 0 ≤ triggers[i] ≤ 10⁷
  • 0 ≤ hold ≤ 10⁷
  • triggers is sorted in non-decreasing order
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRepack the Tray EasyQuiz Score Log EasyMirror and Negate a Bitmap EasySwap Rows and Columns EasyPawns the Rook Can Take Easy
loading Python…
Input
triggers=[2, 3, 10], hold=3
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 123 tests on the server, hidden ones included.