Problem · Hash Table

Total Active Time by Space

Learn this problem
MediumxAI logoxAIFULLTIMEONSITE INTERVIEW

Problem statement

Process records in nondecreasing timestamp order. Each record is [operation, space, user, timestamp].

  • create creates a new Space and makes its creator active at that timestamp.
  • join makes an inactive user active in an existing Space.
  • leave ends that user's current active interval in the Space.

The active-time contribution of a completed interval is leaveTimestamp - startTimestamp. Sum every user's completed intervals for each Space.

Return one string space:total per observed Space, ordered by Space name in ascending lexicographic order. Timestamps and totals use 64-bit integer arithmetic.

Function

totalSpaceActiveTime(records: String[][]) → String[]

Examples

Example 1

records = [["create","abc","user_1","1234567000"],["join","abc","user_2","1234567100"],["leave","abc","user_2","1234567300"],["create","def","user_2","1234568000"],["leave","def","user_2","1234568500"],["leave","abc","user_1","1234569000"]]return = ["abc:2200","def:500"]

In abc, user_1 contributes 2000 and user_2 contributes 200. In def, user_2 contributes 500.

Example 2

records = [["create","alpha","u1","5"],["leave","alpha","u1","5"],["join","alpha","u1","8"],["leave","alpha","u1","13"],["create","beta","u2","10"],["leave","beta","u2","12"]]return = ["alpha:5","beta:2"]

A user may rejoin after leaving. The zero-duration first interval in alpha contributes nothing; its second interval contributes 5.

Constraints

  • 1 <= records.length <= 200000.
  • Every record has exactly four strings.
  • operation is create, join, or leave.
  • 0 <= timestamp <= 10^18, and timestamps are nondecreasing.
  • Space and user names are non-empty ASCII strings without :.
  • Every create or join has exactly one later matching leave; lifecycle operations are valid.

More xAI problems

drafts saved locally
public String[] totalSpaceActiveTime(String[][] records) {
    // Write your code here.
}
records[["create","abc","user_1","1234567000"],["join","abc","user_2","1234567100"],["leave","abc","user_2","1234567300"],["create","def","user_2","1234568000"],["leave","def","user_2","1234568500"],["leave","abc","user_1","1234569000"]]
expected["abc:2200", "def:500"]
checking account