Problem · Array

Shared Counter Snapshot Sum

Learn this problem
MediumTesla logoTeslaFULLTIMEONSITE INTERVIEW

Problem statement

Simulate two workers that atomically increment one shared counter, initially 0.

  • An event "THRESHOLD" asks the threshold worker to increment the counter if that worker is still active.
  • An event "TIMER" asks the timer worker to increment the counter if that worker is still active.
  • The one event "TIMEOUT" represents the timer worker's one-second deadline.

Immediately after any applied increment first makes the counter equal to 10, the threshold worker records a snapshot of 10 and exits. When "TIMEOUT" is processed, the timer worker records the current counter and exits. Events for an exited worker are ignored.

The input sequence contains exactly one timeout and guarantees that both snapshots are recorded before the sequence ends. Return the sum of the two snapshots.

Function

sumSnapshots(events: String[]) → int

Examples

Example 1

events = ["THRESHOLD","TIMER","THRESHOLD","TIMER","THRESHOLD","TIMER","THRESHOLD","TIMER","THRESHOLD","TIMER","TIMEOUT"]return = 20

The tenth increment records the threshold snapshot as 10. The following timeout records 10, so the sum is 20.

Example 2

events = ["TIMER","TIMEOUT","THRESHOLD","THRESHOLD","THRESHOLD","THRESHOLD","THRESHOLD","THRESHOLD","THRESHOLD","THRESHOLD","THRESHOLD"]return = 11

The timer snapshot is 1. The timer then exits, and nine threshold increments raise the counter to 10, producing a total of 11.

Example 3

events = ["THRESHOLD","THRESHOLD","THRESHOLD","THRESHOLD","THRESHOLD","TIMER","TIMER","TIMER","TIMER","TIMER","TIMER","TIMER","TIMEOUT"]return = 22

The fifth timer increment is the tenth total increment, so the threshold snapshot is 10. Two more timer increments occur before timeout records 12.

Constraints

  • 1 <= events.length <= 200000.
  • Every event is "THRESHOLD", "TIMER", or "TIMEOUT".
  • The sequence contains exactly one "TIMEOUT".
  • The sequence guarantees that both snapshots are recorded before it ends.

More Tesla problems

drafts saved locally
public int sumSnapshots(String[] events) {
  // write your code here
}
events["THRESHOLD","TIMER","THRESHOLD","TIMER","THRESHOLD","TIMER","THRESHOLD","TIMER","THRESHOLD","TIMER","TIMEOUT"]
expected20
checking account