- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 31 lines of Java from the credited upstream file 1797.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1public class AuthenticationManager {2 public AuthenticationManager(int timeToLive) {3 this.timeToLive = timeToLive;4 }5 6 public void generate(String tokenId, int currentTime) {7 tokenIdToExpiryTime.put(tokenId, currentTime);8 times.add(currentTime);9 }10 11 public void renew(String tokenId, int currentTime) {12 Integer expiryTime = tokenIdToExpiryTime.get(tokenId);13 if (expiryTime == null || currentTime >= expiryTime + timeToLive)14 return;15 times.remove(expiryTime);16 tokenIdToExpiryTime.put(tokenId, currentTime);17 times.add(currentTime);18 }19 20 public int countUnexpiredTokens(int currentTime) {21 final int expiryTimeThreshold = currentTime - timeToLive + 1;22 23 times.headSet(expiryTimeThreshold).clear();24 return times.size();25 }26 27 private final int timeToLive;28 private final Map<String, Integer> tokenIdToExpiryTime = new HashMap<>();29 private final TreeSet<Integer> times = new TreeSet<>();30}31