FastPrepButton Combination Detector

Button Combination Detector

SpaceX logoSpaceX● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Button Combination Detector

A device produces a finite sequence of button events. Every event has the form down:BUTTON or up:BUTTON, where BUTTON is a case-sensitive label.

No buttons are pressed initially. Process the events in order and return true if, after any event, every label in requiredButtons is pressed at the same time. Other buttons may also be pressed. Return false if the required combination never occurs.

Pressing an already pressed button or releasing a button that is not pressed is a valid no-op.

Function

wasButtonCombinationPressed(events: String[], requiredButtons: String[]) → boolean

Examples

Example 1

events = ["down:A","down:B","up:A"]requiredButtons = ["A","B"]return = true

After processing down:B, both A and B are pressed, so the required combination occurs.

Example 2

events = ["down:A","up:A","down:B","down:A"]requiredButtons = ["A","B"]return = true

The first press of A is released before B is pressed. The final event presses A again while B is still down.

Example 3

events = ["down:A","down:C","up:C"]requiredButtons = ["A","B"]return = false

Button B is never pressed, so the required combination never occurs.

Constraints

  • 1 ≤ events.length ≤ 100,000
  • 1 ≤ requiredButtons.length ≤ 100
  • Every required label is unique and matches [A-Za-z0-9_-]{1,20}.
  • Every event is exactly down:BUTTON or up:BUTTON for a valid label.

More SpaceX problems

See SpaceX hiring insights
public boolean wasButtonCombinationPressed(String[] events, String[] requiredButtons) {
    // Write your code here.
}
events["down:A","down:B","up:A"]
requiredButtons["A","B"]
expectedtrue
Checking account…