#1797
Medium Algorithms Design authentication manager
Hash Table Linked List Design Doubly-Linked List
58.4% acceptance
Feb 23, 2026
430
57
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.
Solution
Rust
Time O(2^n)
Space O(n)
use std::collections::HashMap;
pub struct AuthenticationManager {
time_to_live: i32,
tokens: std::cell::RefCell<HashMap<String, i32>>,
}
impl AuthenticationManager {
pub fn new(time_to_live: i32) -> Self {
AuthenticationManager {
time_to_live,
tokens: std::cell::RefCell::new(HashMap::new()),
}
}
pub fn generate(&self, token_id: String, current_time: i32) {
self.tokens.borrow_mut().insert(token_id, current_time + self.time_to_live);
}
pub fn renew(&self, token_id: String, current_time: i32) {
let mut tokens = self.tokens.borrow_mut();
if let Some(expiry) = tokens.get_mut(&token_id) {
if *expiry > current_time {
*expiry = current_time + self.time_to_live;
}
}
}
pub fn count_unexpired_tokens(&self, current_time: i32) -> i32 {
self.tokens.borrow().values().filter(|&&e| e > current_time).count() as i32
}
}