Engineering platform~15 min2s · 256 MBtarget O(n + q) time, O(n) spacehashing
A team-chat product bills each workspace by seats. A seat is used by a user who has joined and not yet left. People join and leave all the time, and sometimes the same event is sent twice.
Billing charges for the high-water mark: the most seats a workspace used at any one moment. Finance has the full event log and asks about a list of workspaces.
Write peak_seats(workspaces, users, actions, queries).
i is about user users[i] in workspace workspaces[i]. When actions[i] == 1 the user joins, and when actions[i] == 0 the user leaves. The events are in the order they happened.queries, return the largest number of seats that workspace used after any event. A workspace with no events returns 0.Input: workspaces = [1, 1, 2, 1, 1, 1, 2, 1, 1], users = [10, 11, 10, 10, 12, 11, 10, 13, 11], actions = [1, 1, 1, 0, 1, 1, 0, 1, 0], queries = [1, 2, 3]
Output: [3, 1, 0]The trace keeps the set of users in each workspace and the peak.
| i | Event | Workspace 1 after the event | Workspace 2 after the event | Peaks (1, 2) |
|---|---|---|---|---|
| 0 | user 10 joins 1 | 10 | empty | (1, 0) |
| 1 | user 11 joins 1 | 10, 11 | empty | (2, 0) |
| 2 | user 10 joins 2 | 10, 11 | 10 | (2, 1) |
| 3 | user 10 leaves 1 | 11 | 10 | (2, 1) |
| 4 | user 12 joins 1 | 11, 12 | 10 | (2, 1) |
| 5 | user 11 joins 1 again | 11, 12 | 10 | (2, 1) |
| 6 | user 10 leaves 2 | 11, 12 | empty | (2, 1) |
| 7 | user 13 joins 1 | 11, 12, 13 | empty | (3, 1) |
| 8 | user 11 leaves 1 | 12, 13 | empty | (3, 1) |
The queries ask for workspaces 1, 2 and 3. Their peaks are 3, 1 and 0, because workspace 3 never appears.
Input: workspaces = [5, 5], users = [1, 1], actions = [0, 1], queries = [5]
Output: [1]User 1 leaves a workspace they never joined, which changes nothing. Then they join, so the peak is 1.
Input: workspaces = [7, 7], users = [1, 1], actions = [1, 1], queries = [7, 7]
Output: [1, 1]Joining twice uses one seat. The same query appears twice, and it gets the same answer twice.
1 ≤ workspaces.length ≤ 100,000 (events); users and actions have the same length1 ≤ workspaces[i], users[i] ≤ 1,000,000,000 (identifiers)actions[i] is 0 or 11 ≤ queries.length ≤ 100,000, 1 ≤ queries[q] ≤ 1,000,000,000Replaying the whole log for each query costs about n × q, about 10^10 steps. One replay in order, keeping a set of members and a peak for every workspace, answers all the queries from a map. The sets are needed because a repeated join or leave must not change the count.