Problem · Design

Key-Value Store with Hit Counter

Learn this problem
MediumDatabricks logoDatabricksFULLTIMEONSITE INTERVIEW

Problem statement

Process an ordered batch of operations on a string key-value store. The store also records every GET as a hit for the requested key, including a request for a missing key.

Operations

  • PUT|timestamp|key|value: set or overwrite key with value. Return OK.
  • GET|timestamp|key: record one hit for key, then return VALUE:value when the key exists or NULL when it does not.
  • COUNT_HITS|timestamp|key|start|end: return the number of recorded hits for key whose timestamps are in the half-open interval [start, end).

Operation timestamps are nondecreasing. Operations that share a timestamp are processed in input order. Return one result string for every operation, in the same order.

Function

runStore(operations: String[]) → String[]

Examples

Example 1

operations = ["PUT|1|a|red","GET|2|a","GET|3|missing","COUNT_HITS|4|a|0|4","COUNT_HITS|5|missing|3|4","PUT|6|a|blue","GET|7|a","COUNT_HITS|8|a|2|8"]return = ["OK","VALUE:red","NULL","1","1","OK","VALUE:blue","2"]

The first count includes the hit on a at time 2. The missing lookup at time 3 is also recorded. After the overwrite, the lookup at time 7 returns blue, while the hit history for a contains both times 2 and 7.

Example 2

operations = ["GET|1|x","PUT|1|x|one","GET|1|x","COUNT_HITS|1|x|0|1","COUNT_HITS|2|x|1|2"]return = ["NULL","OK","VALUE:one","0","2"]

Both lookups at time 1 count as hits. The half-open interval [0, 1) excludes them, while [1, 2) includes both. Input order determines that the second lookup sees the newly stored value.

Constraints

  • 1 <= operations.length <= 5000
  • Every operation uses one of the documented formats and contains no | inside a key or value.
  • Timestamps are integers in [0, 10^9] and are nondecreasing across the input.
  • Keys and values are non-empty lowercase English strings of length at most 30.
  • For every count operation, 0 <= start <= end <= timestamp + 1.

More Databricks problems

drafts saved locally
public String[] runStore(String[] operations) {
    // Write your code here
}
operations["PUT|1|a|red","GET|2|a","GET|3|missing","COUNT_HITS|4|a|0|4","COUNT_HITS|5|missing|3|4","PUT|6|a|blue","GET|7|a","COUNT_HITS|8|a|2|8"]
expected["OK", "VALUE:red", "NULL", "1", "1", "OK", "VALUE:blue", "2"]
checking account