LeetCode 1797: Design Authentication Manager
Problem Description
Explanation
To solve this problem, we can use a hashmap to store the expiration time of each token. When generating a new token, we update the expiration time for that token in the hashmap. When renewing a token, we check if it exists in the hashmap and if it has not expired, then we update its expiration time. When counting unexpired tokens, we iterate through the hashmap and count the number of tokens that have not expired yet.
Time Complexity
- Generating and renewing tokens will have a time complexity of O(1) as it involves updating the expiration time in the hashmap.
- Counting unexpired tokens will have a time complexity of O(n), where n is the number of tokens in the hashmap.
Space Complexity
- The space complexity will be O(n), where n is the number of unique tokens generated.
Solutions
import java.util.HashMap;
class AuthenticationManager {
private int timeToLive;
private HashMap<String, Integer> tokens;
public AuthenticationManager(int timeToLive) {
this.timeToLive = timeToLive;
this.tokens = new HashMap<>();
}
public void generate(String tokenId, int currentTime) {
tokens.put(tokenId, currentTime + timeToLive);
}
public void renew(String tokenId, int currentTime) {
if (tokens.containsKey(tokenId) && tokens.get(tokenId) > currentTime) {
tokens.put(tokenId, currentTime + timeToLive);
}
}
public int countUnexpiredTokens(int currentTime) {
int count = 0;
for (int expiryTime : tokens.values()) {
if (expiryTime > currentTime) {
count++;
}
}
return count;
}
}
Loading editor...