Design Authentication Manager — LeetCode 1797 Python Solution

MediumDesignHash TableLinked ListDoubly-Linked List
Problem
#1797
Reading time
5 min

The problem

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.

Example

Input
["AuthenticationManager", "renew", "generate", "countUnexpiredTokens", "generate", "renew", "renew", "countUnexpiredTokens"]
Output
[null, null, null, 1, null, null, null, 0]
Explanation
AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with timeToLive = 5 seconds.

Python solution

Python
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)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of key-value pairs in the hash table d auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 1797. Design Authentication Manager is filed here because LeetCode tags it Linked List and Doubly-Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1797. Design Authentication Manager?
LeetCode 1797. Design Authentication Manager is rated Medium on LeetCode.
What is the time complexity of LeetCode 1797. Design Authentication Manager?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1797. Design Authentication Manager?
The Python solution on this page uses O(n), where n is the number of key-value pairs in the hash table d auxiliary space.
What topics does LeetCode 1797. Design Authentication Manager cover?
LeetCode 1797. Design Authentication Manager is tagged Design, Hash Table, Linked List and Doubly-Linked List on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview