Design a token manager that tracks authentication tokens with a fixed time-to-live (TTL). Each token is valid in the half-open time interval [createdTime, createdTime + timeToLive).
You must support the following operations:
TokenManager(timeToLive)
: initialize the manager with a positive integer TTL.
generate(tokenId, currentTime)
: create a new token with id
tokenId
at
currentTime
. If
tokenId
already exists, overwrite it with the new creation time.
renew(tokenId, currentTime)
: if
tokenId
exists and is
unexpired
at
currentTime
, update its creation time to
currentTime
(thus extending its expiry). If it does not exist or is expired, do nothing.
countUnexpiredTokens(currentTime)
: return the number of tokens that are unexpired at
currentTime
.
Requirement: implement efficiently using a lazy deletion strategy for expired tokens (i.e., remove expired entries only when needed, rather than scanning all tokens each time).
1 <= timeToLive <= 10^8
2 * 10^5
total operations
1 <= currentTime <= 10^9
tokenId
is a string of length
1..20
containing letters/digits
Assume timeToLive = 5.
generate("abc", 1)
→ token
abc
valid until time
6
renew("abc", 5)
→ token
abc
valid until time
10
countUnexpiredTokens(6)
→ returns
1
countUnexpiredTokens(10)
→ returns
0
(expires at
10
)