Taro Logo

Design Authentication Manager

#1 Most AskedMedium
0 views
Topics:
ArraysStrings

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 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 of tokenId.
  • The values of currentTime across all the function calls will be strictly increasing.
  • At most 2000 calls will be made to all functions combined.

Solution


Clarifying Questions

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:

  1. What data type should be used for the time parameter (e.g., integer or float), and can we assume the `currentTime` passed to functions is strictly non-decreasing?
  2. If a token with a specific ID is renewed or generated at exact time `t`, and its time-to-live is `TTL`, does it expire strictly at `t + TTL` (meaning it is invalid at `t + TTL`)?
  3. Can `renew` or `generate` be called with a token ID that already exists, and if so, how should `generate` handle duplicate IDs?
  4. Is it possible for `renew` to be called on a token that has already expired or does not exist, and what should it return in that case?
  5. How are the `currentTime` arguments across different method calls ordered? Are they guaranteed to be monotonically increasing?

Brute Force Solution

Approach

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:

  1. Whenever a new person arrives, write their name and their specific expiration time down in your journal.
  2. If someone tries to renew their pass, flip through every single entry in your journal until you find their name, check if their time has already passed, and if not, erase their old time and write down a brand new expiration time.
  3. Whenever someone asks how many people currently have valid passes, look at every single entry recorded in your journal from the very beginning.
  4. For each entry you look at, compare its expiration time against the current time to see if the pass has expired or is still active.
  5. Count up all the entries where the expiration time is still in the future, ignoring the ones that have already expired.
  6. Give that final count as your answer.

Code Implementation

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_count

Big(O) Analysis

Time Complexity
O(n) – For both the pass renewal and the count active passes operations, we must inspect the entire journal of size n to find entries or evaluate expiration times. Each request scans all currently recorded tokens sequentially from the beginning to the end. This leads to approximately n operations per function call, which simplifies to O(n).
Space Complexity
O(N) – The auxiliary space is driven by the journal that records every unique person and their corresponding expiration time in a hash map, where N is the total number of active or recently renewed passes. As new individuals check in, additional key-value pairs are stored in this lookup structure, causing the memory consumption to grow linearly with the number of unique entries. Auxiliary variables used during renewal and counting operations require only a constant amount of extra memory. Consequently, the overall extra space required simplifies to Big O of N.

Optimal Solution

Approach

To 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:

  1. When a new pass is generated for a user, record their unique name alongside the exact future moment when their pass is scheduled to expire in our digital record book.
  2. Whenever a user performs an action, instantly look up their specific record to find their current expiration deadline.
  3. Compare the current time against the expiration deadline to determine if the pass is still valid or has already expired.
  4. If the pass is still valid, update the record with a new, extended expiration deadline based on the requested duration.
  5. If the pass has already expired, treat it as non-existent.
  6. When asked to count how many passes are currently active, quickly review all entries in the digital record book and count only the ones whose expiration deadlines lie strictly in the future.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – For generating, renewing, and verifying a pass, looking up or updating a user ID in the digital record book takes constant time O(1). However, when counting active passes, we must iterate through all n entries currently stored in the record book. In the worst-case scenario, this requires inspecting every single one of the n records to compare their expiration deadlines against the current time. This review process totals n operations, which simplifies directly to O(n).
Space Complexity
O(n) – We maintain a hash map as our digital record book to store each user ID alongside their specific expiration time. In the worst-case scenario where n unique passes are generated, the hash map holds n entries in memory. Therefore, the auxiliary space complexity scales linearly with the total number of active passes, resulting in O(n) extra memory.

Edge Cases

Renewing or counting a token exactly at its expiration timestamp
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The count operation should dynamically verify expiration against the current time and ideally clean up expired tokens to maintain optimal performance.
0/3 completed