Design a recent user query cache that stores query results for quick retrieval. The cache has a fixed capacity and removes the least recently used query whenever space is required.
RecentQueryCache
public RecentQueryCache(int capacity)
capacity distinct queries.public void storeQueryResult(String query, String result)
result for query.public String getQueryResult(String query)
query exists in the cache."" when the query is not present.getQueryResult operation and is never supplied as a query or result.storeQueryResult operation must run in O(1) average time.getQueryResult operation must run in O(1) average time.O(capacity) space.1 ≤ capacity ≤ 100,0001 ≤ query.length() ≤ 2001 ≤ result.length() ≤ 1,000100,000 method calls are made after construction. RecentQueryCache cache = new RecentQueryCache(capacity = 3) cache.storeQueryResult( query = "weather in patna", result = "Sunny") cache.storeQueryResult( query = "java hashmap", result = "Key-value collection") cache.getQueryResult( query = "weather in patna") returns "Sunny" cache.storeQueryResult( query = "train status", result = "On time") cache.storeQueryResult( query = "flood update", result = "Normal") cache.getQueryResult( query = "java hashmap") returns "" cache.getQueryResult( query = "weather in patna") returns "Sunny"Retrieving "weather in patna" makes it recently used. Therefore, "java hashmap" is removed when the fourth distinct query is stored.
RecentQueryCache cache = new RecentQueryCache(capacity = 2) cache.storeQueryResult( query = "electric cars", result = "Initial result") cache.storeQueryResult( query = "battery laptops", result = "Laptop result") cache.storeQueryResult( query = "electric cars", result = "Updated result") cache.storeQueryResult( query = "water purifier", result = "Purifier result") cache.getQueryResult( query = "electric cars") returns "Updated result" cache.getQueryResult( query = "battery laptops") returns ""Updating "electric cars" changes its result and makes it the most recently used query. Consequently, "battery laptops" is removed when "water purifier" is stored.
RecentQueryCache cache = new RecentQueryCache(capacity = 2) cache.storeQueryResult( query = "query-a", result = "result-a") cache.storeQueryResult( query = "query-b", result = "result-b") cache.getQueryResult( query = "missing-query") returns "" cache.storeQueryResult( query = "query-c", result = "result-c") cache.getQueryResult( query = "query-a") returns "" cache.getQueryResult( query = "query-b") returns "result-b"The unsuccessful retrieval of "missing-query" does not change recency. Therefore, "query-a" remains the least recently used query and is removed when "query-c" is stored.