Problem
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive
seconds after the currentTime
. If the token is renewed, the expiry time will be extended to expire timeToLive
seconds after the (potentially different) currentTime
.
Implement the AuthenticationManager
class:
AuthenticationManager(int timeToLive)
constructs theAuthenticationManager
and sets thetimeToLive
.generate(string tokenId, int currentTime)
generates a new token with the giventokenId
at the givencurrentTime
in seconds.renew(string tokenId, int currentTime)
renews the unexpired token with the giventokenId
at the givencurrentTime
in seconds. If there are no unexpired tokens with the giventokenId
, the request is ignored, and nothing happens.countUnexpiredTokens(int currentTime)
returns the number of unexpired tokens at the given currentTime.
Note that if a token expires at time t
, and another action happens on time
t
(renew
or countUnexpiredTokens
), the expiration takes place before the other actions.
Examples
Example 1
|
|
Constraints
1 <= timeToLive <= 10^8
1 <= currentTime <= 10^8
1 <= tokenId.length <= 5
tokenId
consists only of lowercase letters.- All calls to
generate
will contain unique values oftokenId
. - The values of
currentTime
across all the function calls will be strictly increasing. - At most
2000
calls will be made to all functions combined.
Solution
Method 1 – Hash Map for Token Expiry Tracking
Intuition
We need to efficiently generate, renew, and count unexpired tokens. Since currentTime
is strictly increasing, we can use a hash map to store each token’s expiry time and simply remove expired tokens during count or renew operations.
Approach
- Use a hash map to store
tokenId
and its expiry time. - On
generate(tokenId, currentTime)
, set the expiry time tocurrentTime + timeToLive
. - On
renew(tokenId, currentTime)
, if the token exists and is unexpired, update its expiry time tocurrentTime + timeToLive
. - On
countUnexpiredTokens(currentTime)
, remove all expired tokens and return the count of remaining tokens.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(nnnxxxnnn)
- 🧺 Space complexity:
O(nnnxxx)