Problem 1797

Abstract / Summary

Design a system that tracks user time of last login and checks if a user can access based on time constraints.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1797.py

class AuthenticationManager:
    def __init__(self, timeToLive: int):
        self.ttl    = timeToLive
        self.tokens = {}

    def generate(self, tokenId: str, currentTime: int) -> None:
        deadline = currentTime + self.ttl
        self.tokens[tokenId] = deadline

    def renew(self, tokenId: str, currentTime: int) -> None:
        if tokenId in self.tokens:
            deadline = currentTime + self.ttl
            if  self.tokens[tokenId] > currentTime:
                self.tokens[tokenId] = deadline # similar to generate()

    def countUnexpiredTokens(self, currentTime: int) -> int:
        return sum(1 for t in self.tokens if self.tokens[t] > currentTime)
17 lines | 696 bytes | submitted October 18, 2023 | GitHub   7% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (100k+ submissions).

Typical patterns to solve this problem:
  • Design
  • Doubly Linked List
  • Hash Table
  • Linked List
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided AuthenticationManager class implements a lightweight token-based authentication system with a fixed time-to-live (TTL) for each token. It stores token identifiers together with their expiration timestamps and offers three public operations: creating a token, renewing an existing token, and counting the number of tokens that are still valid at a given moment. The implementation relies on a dictionary (self.tokens) for constant-time look-ups and updates, which makes the core operations efficient even as the number of tokens grows.

Initialization

def __init__(self, timeToLive: int):
    self.ttl    = timeToLive
    self.tokens = {}

When an AuthenticationManager instance is created, the TTL value is saved in self.ttl. An empty dictionary self.tokens is prepared to map each tokenId to its absolute expiration time. The dictionary choice enables O(1) access for later operations.

Token Generation

def generate(self, tokenId: str, currentTime: int) -> None:
    deadline = currentTime + self.ttl
    self.tokens[tokenId] = deadline

The generate method computes the expiration moment (deadline) by adding the stored TTL to the supplied currentTime. It then inserts or overwrites the entry for tokenId in the dictionary with this deadline. Overwriting is safe because a newly generated token with the same identifier is expected to replace any prior instance.

Token Renewal

def renew(self, tokenId: str, currentTime: int) -> None:
    if tokenId in self.tokens:
        deadline = currentTime + self.ttl
        if  self.tokens[tokenId] > currentTime:
            self.tokens[tokenId] = deadline  # similar to generate()

Renewal first checks whether the token identifier exists in the dictionary. If it does, a new deadline is calculated. The second condition verifies that the stored deadline is still in the future relative to currentTime. Only when the token has not yet expired does the method update the expiration timestamp, effectively extending its lifetime. This guard prevents a stale token from being resurrected after its TTL has elapsed.

Counting Unexpired Tokens

def countUnexpiredTokens(self, currentTime: int) -> int:
    return sum(1 for t in self.tokens if self.tokens[t] > currentTime)

The counting routine iterates over the keys of self.tokens and increments a total for each token whose stored deadline exceeds currentTime. The use of a generator expression inside sum keeps the memory footprint low because it does not create an intermediate list.

Edge Cases Handled

The code explicitly addresses several boundary conditions:

  • When generate is called with a tokenId that already exists, the previous deadline is overwritten, ensuring that the most recent generation time dictates the token’s validity.
  • In renew, the existence check (if tokenId in self.tokens) prevents a KeyError for unknown identifiers.
  • The second guard in renew (self.tokens[tokenId] > currentTime) ensures that a token that has already reached its expiration moment is not refreshed, preserving the intended TTL semantics.
  • The counting method treats tokens with a deadline equal to currentTime as expired, because the comparison uses a strict greater-than operator. This aligns with the typical interpretation that a token expires exactly at its deadline.

Performance Optimizations

The design leverages the constant-time characteristics of Python dictionaries for both lookup and update operations. By storing the absolute expiration timestamp rather than a relative counter, the code avoids repeated arithmetic during each check; the only calculation required is a single addition when a token is generated or renewed.

The countUnexpiredTokens method uses a generator expression, which yields each token’s status on demand without allocating a full list of boolean values. This approach minimizes temporary memory usage, especially when the token set is large.

Because the dictionary holds only active tokens, the memory consumption grows linearly with the number of distinct identifiers that have been generated and not yet expired. No additional data structures (such as priority queues or sorted lists) are introduced, keeping the implementation simple and fast for typical usage patterns where token expiration checks are performed frequently.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a busy clubhouse that uses special passes for entry. The computer code acts like a clubhouse guard who keeps track of who is inside.

When the clubhouse first opens, it sets a rule about how long a pass stays good, which is like a timer.

To create a new pass, the guard takes a name and the current time. The guard then adds the time limit to the current time to figure out exactly when that pass expires. This date is written down in a notebook next to the name.

If a friend wants to keep their pass for longer, they can ask to renew it. The guard first checks the notebook to see if the name is there. If it is, and if the pass has not already expired, the guard calculates a brand new time limit and updates the notebook.

Sometimes, the guard needs to know how many people are still allowed in the clubhouse. The guard goes through the whole notebook and looks at every single pass. If the time written there is still in the future, it means the pass is fresh and works, so the guard counts it up.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.77 | σ = 1.42

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
DimitrisJim JS
fartem Ruby
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
DimitrisJim JavaScript
fartem Ruby
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
27 links | 15 authors | 9 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 medium 1 hard
4 solutions   October 18, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality