#1797
Design Authentication Manager
MediumHash TableLinked ListDesignDoubly-Linked ListHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a HashMap to store tokens along with their expiry times, allowing for O(1) access to check and update tokens. This significantly reduces the time complexity for renewals and counts.
⚙️
Algorithm
4 steps- 1Step 1: Use a HashMap to store tokenId as the key and its expiry time as the value.
- 2Step 2: For 'generate', simply add the tokenId and its expiry time to the HashMap.
- 3Step 3: For 'renew', check if the tokenId exists and if it is unexpired; if so, update its expiry time.
- 4Step 4: For 'countUnexpiredTokens', iterate through the HashMap and count tokens that are still valid.
solution.py14 lines
1class AuthenticationManager:
2 def __init__(self, timeToLive: int):
3 self.timeToLive = timeToLive
4 self.tokens = {}
5
6 def generate(self, tokenId: str, currentTime: int) -> None:
7 self.tokens[tokenId] = currentTime + self.timeToLive
8
9 def renew(self, tokenId: str, currentTime: int) -> None:
10 if tokenId in self.tokens and self.tokens[tokenId] > currentTime:
11 self.tokens[tokenId] = currentTime + self.timeToLive
12
13 def countUnexpiredTokens(self, currentTime: int) -> int:
14 return sum(1 for expiry in self.tokens.values() if expiry > currentTime)ℹ
Complexity note: The time complexity is O(n) for counting unexpired tokens because we may need to check each token once. The space complexity is O(n) due to storing tokens in a HashMap.
- 1Using a HashMap allows for efficient token management and quick access to token expiry times.
- 2Understanding the implications of token expiration timing is crucial for implementing renewals correctly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.