AlgoMaster Logo
AlgoMasterImplement a DNS TTL Cachemedium

Implement a DNS TTL Cache

medium

DNS records are cacheable only for their time to live (TTL). This limits query load, but it also means a changed authoritative answer does not instantly replace copies already held by resolvers.

Design a DnsTtlCache class:

  • DnsTtlCache() creates an empty cache.
  • void store(String name, String value, int ttlSeconds, int now) stores or replaces a result.
  • String resolve(String name, int now) returns the cached value or "MISS".

DNS names are case-insensitive, but stored values must be returned unchanged. A record stored at time t with TTL d is valid only while now < t + d. Resolving does not refresh its expiration. The value "NXDOMAIN" represents a negative DNS answer and follows the same TTL rules.

Calls on one object use nondecreasing now values.

Example 1:

Input:

Output:

Explanation: The expiration time is 100 + 10 = 110. The entry is valid at 109 and expired at 110.

Example 2:

Input:

Output:

Explanation: Case variants identify the same DNS name. Negative answers are cached to avoid repeatedly querying for a nonexistent name.

Constraints

  • 1 <= name.length, value.length <= 255
  • Names contain only ASCII letters, digits, dots, and hyphens.
  • value != "MISS"
  • 0 <= ttlSeconds, now <= 10^9
  • Calls on one object have nondecreasing now values.
  • At most 10^4 total method calls are made.
Hints

Loading...
CallReturns
new DnsTtlCache()null
store("api.example", "192.0.2.10", 10, 100)null
resolve("api.example", 109)"192.0.2.10"
resolve("api.example", 110)"MISS"

The record is valid for times 100 through 109 and expires exactly at time 110.

Run checks these cases. Submit also runs a larger hidden set.