Design Authentication Manager

Medium Design Data Structures Hash Map + Heap

Design Authentication Manager is a medium design data structures problem solved with the hash map + heap pattern. The best approach, optimal (linked hash map, evict from the front), runs in O(1) amortised per call time and O(k) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from hash map, scan to count up.

Problem

Design a manager for login tokens that expire after a fixed amount of time. Every token lives for exactly timeToLive time units from the moment it is generated or last renewed.

  • AuthenticationManager(timeToLive) creates the manager and fixes the lifetime of every token.
  • generate(tokenId, currentTime) creates a new token with the given id at time currentTime. It expires at currentTime + timeToLive.
  • renew(tokenId, currentTime) gives the token a fresh lifetime, so that it now expires at currentTime + timeToLive, but only if the token exists and has not expired yet. Renewing a missing or expired token does nothing.
  • countUnexpiredTokens(currentTime) returns how many tokens are still alive at time currentTime.

If a token expires at time t and some other action also happens at time t, the expiry happens first. In other words, a token is alive at time t only if its expiry time is strictly greater than t.

Examples

Example 1

Input
AuthenticationManager(4), generate("red", 1), generate("blue", 2), renew("red", 4), countUnexpiredTokens(5), renew("blue", 6), countUnexpiredTokens(7), generate("green", 8), countUnexpiredTokens(9)
Output
2, 1, 1
Why
Tokens live for 4 time units. red is made at 1 (expires at 5) and blue at 2 (expires at 6). At time 4 red is still alive, so renewing it moves its expiry to 8. At time 5 both are alive: 2. At time 6 blue expires, and an expiry happens before anything else at that moment, so the renew is ignored. At time 7 only red is left: 1. At time 8 red expires and green is made (expires at 12), so the count at 9 is 1.

Example 2

Input
AuthenticationManager(10), renew("ghost", 1), generate("tok", 3), countUnexpiredTokens(12), countUnexpiredTokens(13)
Output
1, 0
Why
Renewing a token that was never generated does nothing. tok expires at 3 + 10 = 13, so it still counts at time 12 but not at time 13.

Constraints

  • 1 <= timeToLive <= 10^8
  • 1 <= currentTime <= 10^8
  • 1 <= tokenId.length <= 5
  • tokenId contains only lowercase letters.
  • Every call to generate uses a tokenId that has not been used before.
  • The values of currentTime across all calls are strictly increasing.
  • At most 2000 calls in total to generate, renew and countUnexpiredTokens.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (2 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Hash map, scan to countO(1) for generate and renew, O(n) for countUnexpiredTokensO(n)
Optimal (linked hash map, evict from the front)O(1) amortised per callO(k)

1Hash map, scan to count

TimeO(1) for generate and renew, O(n) for countUnexpiredTokensMap lookups and writes are O(1) on average; counting visits every token ever generated, up to n of them.
SpaceO(n)One entry per generated token, n in total, since nothing is removed.

Keep a map from tokenId to the time it expires. generate stores currentTime + timeToLive. renew looks the token up and only rewrites its expiry if the token exists and its expiry is still greater than currentTime; a token whose expiry equals currentTime has already expired. countUnexpiredTokens walks over every stored expiry and counts the ones greater than currentTime. Expired tokens are never deleted, which is fine for correctness because their expiry is in the past and only gets further behind.

  1. generate(id, t): expiry[id] = t + timeToLive.
  2. renew(id, t): if id is in the map and expiry[id] > t, set expiry[id] = t + timeToLive.
  3. countUnexpiredTokens(t): count the values in the map that are greater than t.
class AuthenticationManager {
    private final int ttl;
    private final Map<String, Integer> expiry = new HashMap<>();

    public AuthenticationManager(int timeToLive) {
        ttl = timeToLive;
    }

    public void generate(String tokenId, int currentTime) {
        expiry.put(tokenId, currentTime + ttl);
    }

    public void renew(String tokenId, int currentTime) {
        Integer end = expiry.get(tokenId);
        if (end != null && end > currentTime) {
            expiry.put(tokenId, currentTime + ttl);
        }
    }

    public int countUnexpiredTokens(int currentTime) {
        int count = 0;
        for (int end : expiry.values()) {
            if (end > currentTime) count++;
        }
        return count;
    }
}

2Optimal (linked hash map, evict from the front)

TimeO(1) amortised per callEach token is evicted at most once per write, and every write is one call, so all evictions together cost no more than the number of calls. Everything else is O(1) hash map work.
SpaceO(k)Only unexpired tokens are kept, k of them, and k is at most the number of generate calls.

Every write sets expiry = currentTime + timeToLive, and currentTime strictly increases, so a token written later always expires no earlier than one written before it. Keep the live tokens in a linked hash map in the order they were last written: generate appends at the back, and renew removes the token and puts it back at the back with its new expiry. Then the tokens that expire first are always at the front. Before every call, pop tokens off the front while their expiry is at most currentTime. After that cleanup the map holds exactly the live tokens, so renew is a plain lookup and countUnexpiredTokens is just the map's size.

  1. evict(t): while the first entry's expiry <= t, remove it.
  2. generate(id, t): evict(t), then insert id at the back with expiry t + timeToLive.
  3. renew(id, t): evict(t); if id is still in the map, remove it and insert it again at the back with expiry t + timeToLive.
  4. countUnexpiredTokens(t): evict(t), then return the size of the map.
class AuthenticationManager {
    private final int ttl;
    private final LinkedHashMap<String, Integer> expiry = new LinkedHashMap<>();

    public AuthenticationManager(int timeToLive) {
        ttl = timeToLive;
    }

    private void evict(int currentTime) {
        Iterator<Integer> it = expiry.values().iterator();
        while (it.hasNext() && it.next() <= currentTime) it.remove();
    }

    public void generate(String tokenId, int currentTime) {
        evict(currentTime);
        expiry.put(tokenId, currentTime + ttl);
    }

    public void renew(String tokenId, int currentTime) {
        evict(currentTime);
        if (expiry.remove(tokenId) != null) {
            expiry.put(tokenId, currentTime + ttl);
        }
    }

    public int countUnexpiredTokens(int currentTime) {
        evict(currentTime);
        return expiry.size();
    }
}

Edge cases to test

  • renew at exactly the expiry time: the token is already gone, so nothing changes
  • count at exactly the expiry time: the token no longer counts
  • renew of a token that was never generated: ignore it
  • renew of a token that expired long ago: ignore it, it does not come back
  • Renewing moves a token behind tokens that were generated after it, so expiries are not in generate order
  • timeToLive = 1: a token is alive only at the moment it is generated
  • currentTime + timeToLive reaches 2 * 10^8, which still fits in an int

Hints

Hint 1

Each token only needs one number: the time at which it expires. A token is alive at time t exactly when that number is greater than t.

Hint 2

A map from tokenId to expiry time already answers generate and renew. How expensive is counting with it?

Hint 3

Every generate or renew sets expiry = currentTime + timeToLive, and currentTime only grows. So if you keep tokens in the order they were last written, their expiry times are sorted. Which tokens expire first?

Hint 4

A linked hash map keeps that order: remove and re-insert a token on renew to move it to the back, and drop expired tokens from the front.

FAQ

What is the best time complexity for Design Authentication Manager?

Optimal (linked hash map, evict from the front) runs in O(1) amortised per call time and O(k) extra space. Each token is evicted at most once per write, and every write is one call, so all evictions together cost no more than the number of calls. Everything else is O(1) hash map work.

Which pattern does Design Authentication Manager use?

It is a design data structures problem that uses the hash map + heap pattern. Other problems with the same pattern: Cache With Time Limit.

Is there a brute force solution for Design Authentication Manager?

Yes. Hash map, scan to count takes O(1) for generate and renew, O(n) for countUnexpiredTokens time and O(n) space. Keep a map from tokenId to the time it expires.

Which edge cases should I test for Design Authentication Manager?

renew at exactly the expiry time: the token is already gone, so nothing changes; count at exactly the expiry time: the token no longer counts; renew of a token that was never generated: ignore it; renew of a token that expired long ago: ignore it, it does not come back; Renewing moves a token behind tokens that were generated after it, so expiries are not in generate order; timeToLive = 1: a token is alive only at the moment it is generated; currentTime + timeToLive reaches 2 10^8, which still fits in an int.