926. Session Tokens

Medium3.5 points estimatedDesignHash Table4 hints

A server issues login tokens that stay valid for timeToLive time units. Build SessionTokens with that constructor argument.

  • generate(tokenId, currentTime) creates a token that expires at currentTime + timeToLive. The id has never been used before.
  • renew(tokenId, currentTime) pushes the expiry of a live token to currentTime + timeToLive. A token is live only while currentTime is strictly less than its expiry. Unknown or expired ids are ignored.
  • countUnexpiredTokens(currentTime) returns how many tokens are live at that moment.

Times never decrease from one call to the next. Aim for amortised O(1) per call.

Example 1

Input:
operations = ["SessionTokens","generate","generate","countUnexpiredTokens","renew","countUnexpiredTokens","renew","countUnexpiredTokens"]arguments = [[6],["ember",2],["quartz",3],[7],["ember",7],[8],["quartz",9],[13]]
Output:
[null,null,null,2,null,2,null,0]
Explanation:

At time 7 ember (expires at 8) and quartz (expires at 9) are both live, so the count is 2. Renewing ember at 7 moves its expiry to 13, so the count at time 8 is still 2. Quartz expired at time 9, so the renew at 9 is ignored, and at time 13 ember has expired too: the count is 0.

Example 2

Input:
operations = ["SessionTokens","generate","countUnexpiredTokens","countUnexpiredTokens","renew","countUnexpiredTokens"]arguments = [[4],["k9",0],[3],[4],["k9",4],[4]]
Output:
[null,null,1,0,null,0]
Explanation:

The token expires at time 4, so it is already dead at time 4. The renew at time 4 is ignored and the final count is 0.

Constraints

1 ≤ timeToLive ≤ 108

0 ≤ currentTime ≤ 109, non-decreasing over the calls

1 ≤ tokenId.length ≤ 12, lowercase letters and digits

At most 2000 calls in total

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Input
Each case is an operation log. operations names the class first and then each method call; arguments holds the arguments for each, in the same order. Your answer is one list with a result per operation - null for the constructor and for methods that return nothing.

Expected complexity

Time
O(1) amortised per call
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…

operations names the class, then each method to call; arguments holds one list of arguments per operation, in the same order.