Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
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 withtimeToLive= 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 therenewrequest is ignored, and nothing happens. authenticationManager.renew("bbb", 10); // The token with tokenId "bbb" is unexpired at time 10, so therenewrequest 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 <= 1081 <= currentTime <= 1081 <= tokenId.length <= 5tokenId consists only of lowercase letters.generate will contain unique values of tokenId.currentTime across all the function calls will be strictly increasing.2000 calls will be made to all functions combined.Problem summary: 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Linked List · Design
["AuthenticationManager","renew","generate","countUnexpiredTokens","generate","renew","renew","countUnexpiredTokens"] [[5],["aaa",1],["aaa",2],[6],["bbb",7],["aaa",8],["bbb",10],[15]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1797: Design Authentication Manager
class AuthenticationManager {
private int t;
private Map<String, Integer> d = new HashMap<>();
public AuthenticationManager(int timeToLive) {
t = timeToLive;
}
public void generate(String tokenId, int currentTime) {
d.put(tokenId, currentTime + t);
}
public void renew(String tokenId, int currentTime) {
if (d.getOrDefault(tokenId, 0) <= currentTime) {
return;
}
generate(tokenId, currentTime);
}
public int countUnexpiredTokens(int currentTime) {
int ans = 0;
for (int exp : d.values()) {
if (exp > currentTime) {
++ans;
}
}
return ans;
}
}
/**
* 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);
*/
// Accepted solution for LeetCode #1797: Design Authentication Manager
type AuthenticationManager struct {
t int
d map[string]int
}
func Constructor(timeToLive int) AuthenticationManager {
return AuthenticationManager{timeToLive, map[string]int{}}
}
func (this *AuthenticationManager) Generate(tokenId string, currentTime int) {
this.d[tokenId] = currentTime + this.t
}
func (this *AuthenticationManager) Renew(tokenId string, currentTime int) {
if v, ok := this.d[tokenId]; !ok || v <= currentTime {
return
}
this.Generate(tokenId, currentTime)
}
func (this *AuthenticationManager) CountUnexpiredTokens(currentTime int) int {
ans := 0
for _, exp := range this.d {
if exp > currentTime {
ans++
}
}
return ans
}
/**
* 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);
*/
# Accepted solution for LeetCode #1797: Design Authentication Manager
class AuthenticationManager:
def __init__(self, timeToLive: int):
self.t = timeToLive
self.d = defaultdict(int)
def generate(self, tokenId: str, currentTime: int) -> None:
self.d[tokenId] = currentTime + self.t
def renew(self, tokenId: str, currentTime: int) -> None:
if self.d[tokenId] <= currentTime:
return
self.d[tokenId] = currentTime + self.t
def countUnexpiredTokens(self, currentTime: int) -> int:
return sum(exp > currentTime for exp in self.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)
// Accepted solution for LeetCode #1797: Design Authentication Manager
use std::collections::HashMap;
struct AuthenticationManager {
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.
*/
impl AuthenticationManager {
fn new(timeToLive: i32) -> Self {
Self {
time_to_live: timeToLive,
map: HashMap::new(),
}
}
fn generate(&mut self, token_id: String, current_time: i32) {
self.map.insert(token_id, current_time + self.time_to_live);
}
fn renew(&mut self, token_id: String, current_time: i32) {
if self.map.get(&token_id).unwrap_or(&0) <= ¤t_time {
return;
}
self.map.insert(token_id, current_time + self.time_to_live);
}
fn count_unexpired_tokens(&self, current_time: i32) -> i32 {
self.map
.values()
.filter(|&time| *time > current_time)
.count() as i32
}
}
// Accepted solution for LeetCode #1797: Design Authentication Manager
class AuthenticationManager {
private timeToLive: number;
private map: Map<string, number>;
constructor(timeToLive: number) {
this.timeToLive = timeToLive;
this.map = new Map<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 {
let res = 0;
for (const time of this.map.values()) {
if (time > currentTime) {
res++;
}
}
return res;
}
}
/**
* 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)
*/
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.