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 the AuthenticationManager and sets the timeToLive.
generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.
renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId, 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.
Example 1:
Input
["AuthenticationManager", "renew", "generate", "countUnexpiredTokens", "generate", "renew", "renew", "countUnexpiredTokens"]
[[5], ["aaa", 1], ["aaa", 2], [6], ["bbb", 7], ["aaa", 8], ["bbb", 10], [15]]
Output
[null, null, null, 1, null, null, null, 0]
Explanation
AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with timeToLive = 5 seconds.
authenticationManager.renew("aaa", 1); // No token exists with tokenId "aaa" at time 1, so nothing happens.
authenticationManager.generate("aaa", 2); // Generates a new token with tokenId "aaa" at time 2.
authenticationManager.countUnexpiredTokens(6); // The token with tokenId "aaa" is the only unexpired one at time 6, so return 1.
authenticationManager.generate("bbb", 7); // Generates a new token with tokenId "bbb" at time 7.
authenticationManager.renew("aaa", 8); // The token with tokenId "aaa" expired at time 7, and 8 >= 7, so at time 8 the renew request is ignored, and nothing happens.
authenticationManager.renew("bbb", 10); // The token with tokenId "bbb" is unexpired at time 10, so the renew request is fulfilled and now the token will expire at time 15.
authenticationManager.countUnexpiredTokens(15); // The token with tokenId "bbb" expires at time 15, and the token with tokenId "aaa" expired at time 7, so currently no token is unexpired, so return 0.
Constraints:
1 <= timeToLive <= 108
1 <= currentTime <= 108
1 <= tokenId.length <= 5
tokenId consists only of lowercase letters.
All calls to generate will contain unique values of tokenId.
The values of currentTime across all the function calls will be strictly increasing.
At most 2000 calls will be made to all functions combined.
Solutions
Solution 1: Hash Table
We can simply maintain a hash table $d$, where the key is tokenId and the value is the expiration time.
During the generate operation, we store tokenId as the key and currentTime + timeToLive as the value in the hash table $d$.
During the renew operation, if tokenId is not in the hash table $d$, or currentTime >= d[tokenId], we ignore this operation; otherwise, we update d[tokenId] to currentTime + timeToLive.
During the countUnexpiredTokens operation, we traverse the hash table $d$ and count the number of unexpired tokenId.
In terms of time complexity, both generate and renew operations have a time complexity of $O(1)$, and the countUnexpiredTokens operation has a time complexity of $O(n)$, where $n$ is the number of key-value pairs in the hash table $d$.
The space complexity is $O(n)$, where $n$ is the number of key-value pairs in the hash table $d$.
1 2 3 4 5 6 7 8 910111213141516171819202122
classAuthenticationManager:def__init__(self,timeToLive:int):self.t=timeToLiveself.d=defaultdict(int)defgenerate(self,tokenId:str,currentTime:int)->None:self.d[tokenId]=currentTime+self.tdefrenew(self,tokenId:str,currentTime:int)->None:ifself.d[tokenId]<=currentTime:returnself.d[tokenId]=currentTime+self.tdefcountUnexpiredTokens(self,currentTime:int)->int:returnsum(exp>currentTimeforexpinself.d.values())# Your AuthenticationManager object will be instantiated and called as such:# obj = AuthenticationManager(timeToLive)# obj.generate(tokenId,currentTime)# obj.renew(tokenId,currentTime)# param_3 = obj.countUnexpiredTokens(currentTime)
classAuthenticationManager{privateintt;privateMap<String,Integer>d=newHashMap<>();publicAuthenticationManager(inttimeToLive){t=timeToLive;}publicvoidgenerate(StringtokenId,intcurrentTime){d.put(tokenId,currentTime+t);}publicvoidrenew(StringtokenId,intcurrentTime){if(d.getOrDefault(tokenId,0)<=currentTime){return;}generate(tokenId,currentTime);}publicintcountUnexpiredTokens(intcurrentTime){intans=0;for(intexp:d.values()){if(exp>currentTime){++ans;}}returnans;}}/** * Your AuthenticationManager object will be instantiated and called as such: * AuthenticationManager obj = new AuthenticationManager(timeToLive); * obj.generate(tokenId,currentTime); * obj.renew(tokenId,currentTime); * int param_3 = obj.countUnexpiredTokens(currentTime); */
classAuthenticationManager{public:AuthenticationManager(inttimeToLive){t=timeToLive;}voidgenerate(stringtokenId,intcurrentTime){d[tokenId]=currentTime+t;}voidrenew(stringtokenId,intcurrentTime){if(d[tokenId]<=currentTime)return;generate(tokenId,currentTime);}intcountUnexpiredTokens(intcurrentTime){intans=0;for(auto&[_,v]:d)ans+=v>currentTime;returnans;}private:intt;unordered_map<string,int>d;};/** * Your AuthenticationManager object will be instantiated and called as such: * AuthenticationManager* obj = new AuthenticationManager(timeToLive); * obj->generate(tokenId,currentTime); * obj->renew(tokenId,currentTime); * int param_3 = obj->countUnexpiredTokens(currentTime); */
typeAuthenticationManagerstruct{tintdmap[string]int}funcConstructor(timeToLiveint)AuthenticationManager{returnAuthenticationManager{timeToLive,map[string]int{}}}func(this*AuthenticationManager)Generate(tokenIdstring,currentTimeint){this.d[tokenId]=currentTime+this.t}func(this*AuthenticationManager)Renew(tokenIdstring,currentTimeint){ifv,ok:=this.d[tokenId];!ok||v<=currentTime{return}this.Generate(tokenId,currentTime)}func(this*AuthenticationManager)CountUnexpiredTokens(currentTimeint)int{ans:=0for_,exp:=rangethis.d{ifexp>currentTime{ans++}}returnans}/** * Your AuthenticationManager object will be instantiated and called as such: * obj := Constructor(timeToLive); * obj.Generate(tokenId,currentTime); * obj.Renew(tokenId,currentTime); * param_3 := obj.CountUnexpiredTokens(currentTime); */
classAuthenticationManager{privatetimeToLive:number;privatemap:Map<string,number>;constructor(timeToLive:number){this.timeToLive=timeToLive;this.map=newMap<string,number>();}generate(tokenId:string,currentTime:number):void{this.map.set(tokenId,currentTime+this.timeToLive);}renew(tokenId:string,currentTime:number):void{if((this.map.get(tokenId)??0)<=currentTime){return;}this.map.set(tokenId,currentTime+this.timeToLive);}countUnexpiredTokens(currentTime:number):number{letres=0;for(consttimeofthis.map.values()){if(time>currentTime){res++;}}returnres;}}/** * Your AuthenticationManager object will be instantiated and called as such: * var obj = new AuthenticationManager(timeToLive) * obj.generate(tokenId,currentTime) * obj.renew(tokenId,currentTime) * var param_3 = obj.countUnexpiredTokens(currentTime) */
usestd::collections::HashMap;structAuthenticationManager{time_to_live:i32,map:HashMap<String,i32>,}/** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */implAuthenticationManager{fnnew(timeToLive:i32)->Self{Self{time_to_live:timeToLive,map:HashMap::new(),}}fngenerate(&mutself,token_id:String,current_time:i32){self.map.insert(token_id,current_time+self.time_to_live);}fnrenew(&mutself,token_id:String,current_time:i32){ifself.map.get(&token_id).unwrap_or(&0)<=¤t_time{return;}self.map.insert(token_id,current_time+self.time_to_live);}fncount_unexpired_tokens(&self,current_time:i32)->i32{self.map.values().filter(|&time|*time>current_time).count()asi32}}