FastPrepFixed-Order Task Run Time With Cooldown

Fixed-Order Task Run Time With Cooldown

Waymo logoWaymo● MediumFULLTIMEPHONE SCREEN

Problem statement

You are given a string tasks. Each character is a task type, and the tasks must run in exactly the order they appear. You are also given an integer cooldown.

The tasks run on one machine under these rules:

  • Each task takes exactly one second, and only one task can run at a time.
  • You cannot change the order of the tasks.
  • After a task of some type finishes, the next task of the same type can start only after at least cooldown more seconds have passed.
  • While the next task is waiting for its cooldown, the machine stays idle. Tasks of other types and idle seconds both count toward the cooldown.

The first task starts at time 0. Return the total number of seconds needed to finish every task.

Function

taskRunTime(tasks: String, cooldown: int) → int

Examples

Example 1

tasks = "ABBCC"cooldown = 3return = 11

Track when each task starts and ends:

  • A runs from 0 to 1.
  • The first B runs from 1 to 2.
  • The second B must wait until 2 + 3 = 5, so it runs from 5 to 6.
  • The first C runs from 6 to 7.
  • The second C must wait until 7 + 3 = 10, so it runs from 10 to 11.

The last task ends at time 11.

Example 2

tasks = "ABCA"cooldown = 2return = 4

A, B, and C run in the first three seconds. The first A ended at time 1, so the second A may start at 1 + 2 = 3. That is exactly when the machine becomes free, so no idle time is needed and the last task ends at time 4.

Example 3

tasks = "AAA"cooldown = 0return = 3

With a cooldown of 0, tasks of the same type can run back to back. The three tasks end at time 3.

Constraints

  • 1 <= tasks.length <= 10^5
  • tasks contains only uppercase English letters.
  • 0 <= cooldown <= 10^4

More Waymo problems

See Waymo hiring insights
Saved
public int taskRunTime(String tasks, int cooldown) {
    // Write your code here.
}
tasks"ABBCC"
cooldown3
expected11
Checking account…