Teemo Attacking Coding Lab

Easy
81
1
36.9% Acceptance

In this coding lab, you will solve a problem based on Teemo attacking an enemy Ashe with poison attacks! Teemo has a very special attack mechanism where if he attacks an enemy, they get poisoned for an exact duration of seconds. Your task in this lab is to calculate the total seconds during which Ashe is poisoned. You'll improve your skills in working with arrays and time calculations in this lab.

Problem description:

Teemo attacks Ashe with poison, and when Teemo attacks, Ashe gets poisoned for a specific duration, let's say exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.

You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.

Your task is to return the total number of seconds that Ashe is poisoned.

Examples:

Example 1:

Input: timeSeries = [1, 4], duration = 2 Output: 4

In this example, Teemo's attacks on Ashe go as follows:

  • At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
  • At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5. As a result, Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.

Example 2:

Input: timeSeries = [1, 2], duration = 2 Output: 3

In this example, Teemo's attacks on Ashe go as follows:

  • At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
  • At second 2, Teemo attacks again, resetting the poison timer, and Ashe is poisoned for seconds 2 and 3. In this case, Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.

Constraints:

  • 1 <= timeSeries.length <= 104
  • 0 <= timeSeries[i], duration <= 107
  • timeSeries is sorted in non-decreasing order.

By completing this lab, not only will you have a good understanding of a real-world coding problem, but you'll also get hands-on experience with handling arrays and time intervals in JavaScript.

Make sure you're default exporting the function