Recent Metrics by Name and Tags
Learn this problemProblem statement
Implement an in-memory metrics database. Process the rows of operations in order, starting with an empty database.
["RECORD", name, timestamp, value, tag1, ...]stores one metric. Each tag is written askey=value.["SEARCH", name, n, tag1, ...]returns the most recent matching metrics. A stored metric matches when its name is equal and it contains every query tag with the same value; it may contain additional tags.
For each operation, append one row to the result. A RECORD row produces ["null"]. A SEARCH row contains up to n matching metrics ordered by descending timestamp, with later RECORD operations first when timestamps tie.
Encode each returned metric as name|timestamp|value|tags. In that encoding, sort its key=value tags lexicographically and join them with commas. A metric with no tags has an empty suffix after the final |. If fewer than n metrics match, return all of them; if none match or n is zero, return an empty row.
Function
processMetrics(operations: String[][]) → String[][]Examples
Example 1
operations = [["RECORD","cpu","10","7","host=a","zone=west"],["RECORD","cpu","12","9","host=a"],["SEARCH","cpu","2","host=a"]]return = [["null"],["null"],["cpu|12|9|host=a","cpu|10|7|host=a,zone=west"]]Both stored CPU metrics contain host=a. Timestamp 12 comes first, and the older metric may have the additional zone tag.
Example 2
operations = [["RECORD","latency","20","4","region=us"],["RECORD","latency","20","8","region=us","tier=api"],["SEARCH","latency","5","region=us"]]return = [["null"],["null"],["latency|20|8|region=us,tier=api","latency|20|4|region=us"]]The two matching metrics have equal timestamps, so the metric recorded later is returned first. Its tags are sorted in the encoded record.
Example 3
operations = [["RECORD","cpu","1","5","host=a"],["SEARCH","memory","3","host=a"],["SEARCH","cpu","0"]]return = [["null"],[],[]]The name memory has no stored metrics, and a limit of zero also returns an empty result row.
Constraints
1 <= operations.length <= 100.- Every operation begins with
RECORDorSEARCHand follows the row shape in the statement. - Names, tag keys, and tag values contain 1 to 20 lowercase English letters, digits, or underscores.
- Each row contains at most 20 tags with distinct keys.
0 <= timestamp <= 10^9and-10^9 <= value <= 10^9.0 <= n <= 100.