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.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a guest list where people check in with a temporary pass that expires after a certain amount of time, and you need to keep track of who is still allowed inside. The brute force approach relies on keeping a giant journal of every single person and the exact time their pass stops working, checking the whole journal from top to bottom every time someone asks a question.
Here's how the algorithm would work step-by-step:
class AuthenticationManager:
def __init__(self, time_to_live: int):
self.time_to_live_amount = time_to_live
self.token_journal = []
def generate(self, token_id: str, current_time: int) -> None:
# We store every token and its expiration time in a list to track all passes
expiration_timestamp = current_time + self.time_to_live_amount
self.token_journal.append((token_id, expiration_timestamp))
def renew(self, token_id: str, current_time: int) -> None:
# We scan the entire journal to find the matching token and update it if valid
for journal_index in range(len(self.token_journal)):
stored_token, stored_expiration = self.token_journal[journal_index]
if stored_token == token_id:
if stored_expiration > current_time:
new_expiration = current_time + self.time_to_live_amount
self.token_journal[journal_index] = (token_id, new_expiration)
break
def countUnexpiredTokens(self, current_time: int) -> int:
# We must inspect every single entry from the beginning to check expiration
active_token_count = 0
for stored_token, stored_expiration in self.token_journal:
if stored_expiration > current_time:
active_token_count += 1
return active_token_countTo efficiently manage security passes, we use a digital record book that links each user ID directly to their specific expiration time. This allows us to instantly check, update, or count active passes without having to search through every single record one by one.
Here's how the algorithm would work step-by-step:
class AuthenticationManager:
def __init__(self, time_to_live: int):
self.time_to_live = time_to_live
self.token_expiration_map = {}
def generate(self, token_id: str, current_time: int) -> None:
# Store the exact expiration time for this token to enable O(1) lookups.
self.token_expiration_map[token_id] = current_time + self.time_to_live
def renew(self, token_id: str, current_time: int) -> None:
# We only renew tokens that exist and have not yet expired.
if token_id in self.token_expiration_map and self.token_expiration_map[token_id] > current_time:
self.token_expiration_map[token_id] = current_time + self.time_to_live
def count_unexpired_tokens(self, current_time: int) -> int:
active_token_count = 0
# Count only entries whose expiration deadlines lie strictly in the future.
for token_id, expiration_time in self.token_expiration_map.items():
if expiration_time > current_time:
active_token_count += 1
return active_token_count| Case | How to Handle |
|---|---|
| Renewing or counting a token exactly at its expiration timestamp | The system treats expiration as strictly greater than current time, so tokens expiring at current time are correctly considered expired. |
| Renewing a token that has already expired | The renew operation checks if the token exists and its expiration time exceeds the current time, doing nothing if it is expired. |
| Generating a token with an ID that already exists and is still unexpired | Generating a new token with an existing ID overwrites the previous token and resets its expiration time based on the new generation time. |
| Querying unexpired tokens when all existing tokens have expired | The count function iterates through or filters the records and returns zero when no tokens meet the unexpired condition. |
| Time values passed out of chronological order across method calls | Since each method accepts a current time parameter, the implementation must rely solely on these explicit parameters rather than assuming monotonically increasing system clocks. |
| High volume of generate and renew operations leading to performance degradation in counting | Using a hash map to store token IDs and their expiration times allows constant time generation and renewal, while lazy deletion or efficient data structures handle large counts. |
| Extremely large integer values for time parameters | Using standard 64-bit integers prevents overflow issues when adding timeToLive to large time timestamps. |
| Counting unexpired tokens when the data structure contains many expired tokens | The count operation should dynamically verify expiration against the current time and ideally clean up expired tokens to maintain optimal performance. |