Table of Contents
Problem Statement
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.
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 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.
Golang code
/**
* 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);
*/
// Input
// ["AuthenticationManager", [5], null
// "renew", ["aaa", 1], null
// "generate", ["aaa", 2], null
// "countUnexpiredTokens", [6], 1
// "generate", ["bbb", 7], null
// "renew", ["aaa", 8], null
// "renew", ["bbb", 10], null
// "countUnexpiredTokens"] [15] 0
type AuthenticationManager struct {
timeToLive int
// tokenID string
// endTime int
// map[tokenID]endTime
tokenMap map[string]int
}
func Constructor(timeToLive int) AuthenticationManager {
return AuthenticationManager{
timeToLive: timeToLive,
tokenMap: make(map[string]int),
}
}
func (this *AuthenticationManager) Generate(tokenId string, currentTime int) {
this.tokenMap[tokenId] = currentTime + this.timeToLive
}
func (this *AuthenticationManager) Renew(tokenId string, currentTime int) {
// unexpired token condition check
if this.tokenMap[tokenId] > currentTime {
this.tokenMap[tokenId] = currentTime + this.timeToLive
}
}
func (this *AuthenticationManager) CountUnexpiredTokens(currentTime int) int {
count := 0
for _, v := range this.tokenMap {
if v > currentTime {
count++
}
}
return count
}
Output
Case 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]
Optimised code using Heap
Explanation of Optimisations
- Efficient Cleanup:
- The priority queue ensures the smallest expiration time is handled first.
- Expired tokens are removed lazily, avoiding redundant checks over all tokens.
- Fast Operations:
Generate
: O(logn), inserts into the heap and map.Renew
: O(logn), updates the heap and map.CountUnexpiredTokens
: O(klogn), where k is the number of expired tokens at the current time.
- Memory Usage:
- Slightly higher due to the heap, but manageable given constraints (2000 calls).
/**
* 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);
*/
// Input
// ["AuthenticationManager", [5], null
// "renew", ["aaa", 1], null
// "generate", ["aaa", 2], null
// "countUnexpiredTokens", [6], 1
// "generate", ["bbb", 7], null
// "renew", ["aaa", 8], null
// "renew", ["bbb", 10], null
// "countUnexpiredTokens"] [15] 0
type Token struct {
tokenID string
expiryTime int
}
type MinHeap []Token
func (h MinHeap) Less(i, j int) bool {
return h[i].expiryTime < h[j].expiryTime
}
func (h MinHeap) Len() int {
return len(h)
}
func (h MinHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
}
func (h *MinHeap) Push(t interface{}) {
*h = append(*h, t.(Token))
}
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
item := old[n-1]
*h = old[:n-1]
return item
}
type AuthenticationManager struct {
timeToLive int
// tokenID string
// endTime int
// map[tokenID]endTime
tokenMap map[string]int
expiryHeap *MinHeap
}
func Constructor(timeToLive int) AuthenticationManager {
h := &MinHeap{}
heap.Init(h)
return AuthenticationManager{
timeToLive: timeToLive,
tokenMap: make(map[string]int),
expiryHeap: h,
}
}
func (this *AuthenticationManager) Generate(tokenId string, currentTime int) {
this.tokenMap[tokenId] = currentTime + this.timeToLive
heap.Push(this.expiryHeap, Token{
tokenID: tokenId,
expiryTime: this.tokenMap[tokenId],
})
}
func (this *AuthenticationManager) Renew(tokenId string, currentTime int) {
// unexpired token condition check
if expiryTime, exist := this.tokenMap[tokenId]; exist && expiryTime > currentTime {
this.tokenMap[tokenId] = currentTime + this.timeToLive
heap.Push(this.expiryHeap, Token{
tokenID: tokenId,
expiryTime: this.tokenMap[tokenId],
})
}
}
func (this *AuthenticationManager) CountUnexpiredTokens(currentTime int) int {
for this.expiryHeap.Len() > 0 && (*this.expiryHeap)[0].expiryTime <= currentTime {
expiredToken := heap.Pop(this.expiryHeap).(Token)
if expiredToken.expiryTime == this.tokenMap[expiredToken.tokenID] {
delete(this.tokenMap, expiredToken.tokenID)
}
}
return len(this.tokenMap)
// count := 0
// for _, v := range this.tokenMap {
// if v > currentTime {
// count++
// }
// }
// return count
}
Please visit https: https://codeandalgo.com for more such contents.
Leave a Reply