Problem Description
Implement an AuthenticationManager that supports generating tokens with an expiration time, renewing tokens if they are still unexpired, and counting unexpired tokens at any given time. Each token is set to expire after a fixed timeToLive period, and renewed tokens receive an updated expiration time. Actions on the same timestamp as a token’s expiry will see the token as already expired.
Key Insights
- Use a hash table (dictionary) to store token IDs with their corresponding expiration times.
- Since currentTime values are strictly increasing, we can safely check and remove expired tokens during the count operation without worrying about out-of-order timestamps.
- Renewal only occurs if the token hasn’t already expired.
- Even though a more efficient strategy using a priority queue (or sorted list) could be used for larger input sizes, given the maximum of 2000 calls the simpler approach is acceptable in terms of performance.
Space and Time Complexity
Time Complexity:
- generate: O(1)
- renew: O(1)
- countUnexpiredTokens: O(n) in worst-case where n is the number of tokens (since it may iterate over all tokens)
Space Complexity:
- O(n), where n is the number of tokens stored at any time.
Solution
We choose a dictionary (hash table) to map token Ids to their expiration times.
- For generate, insert a new entry with tokenId and expiration = currentTime + timeToLive.
- For renew, check if tokenId exists and its expiration time is greater than currentTime. If yes, update expiration; otherwise, do nothing.
- For countUnexpiredTokens, iterate over the dictionary and count tokens where the stored expiration time is greater than currentTime. Optionally, remove expired tokens to keep the dictionary clean.
This approach leverages the strictly increasing nature of currentTime to ensure expired tokens can be safely pruned when queried.