Search Recorded Metrics by Name, Tags, and Recency
Company: Vercel
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Implement recording and searching for an in-memory collection of metrics. A metric has a name, timestamp, integer value, and string-to-string tags. A search supplies a name, required tags, and a limit `n`, and returns the most recent matching metrics.
For this practice version, one callable first records the supplied metrics in order and then answers each search against the completed collection.
### Input
- `metrics`: an array of records represented as `[name, timestamp, value, tags]`, where `tags` is a string-to-string map.
- `searches`: an array of queries represented as `[name, tags, n]`.
### Output
Return one array of matching metric records for each query, preserving query order. Each returned record has the same four-field representation as the input.
### Matching and Ordering Rules
- Names must match exactly and are case-sensitive.
- For this practice version, every query tag must be present with the same value in a metric's tags. Additional metric tags are allowed. An empty query-tag map imposes no tag restriction.
- “Most recent” means greatest timestamp, regardless of recording order.
- For equal timestamps, return the metric recorded later first.
- Keep duplicate records as separate recorded metrics. Do not collapse them by name, timestamp, or content.
- Return at most `n` matches; fewer are valid when fewer exist. If `n == 0`, return an empty array.
### Constraints and Edge Cases
- For this practice version, `0 <= metrics.length <= 10000` and `1 <= searches.length <= 500`.
- Names and tag keys are nonempty ASCII strings; tag values may be empty strings.
- Timestamps are integers from `0` to `1000000000`, and metric values are integers from `-1000000000` to `1000000000`.
- Each tag map contains at most ten key-value pairs, and `0 <= n <= metrics.length`.
- The total number of returned records across all queries is at most `20000`.
- A query with no matching name or tags returns an empty array.
### Example 1
```text
metrics = [
["cpu",10,1,{"host":"a","env":"prod"}],
["cpu",20,2,{"host":"a"}],
["cpu",20,3,{"host":"b"}],
["memory",30,4,{"host":"a"}]
]
searches = [["cpu",{"host":"a"},2], ["cpu",{},2]]
output = [
[["cpu",20,2,{"host":"a"}], ["cpu",10,1,{"host":"a","env":"prod"}]],
[["cpu",20,3,{"host":"b"}], ["cpu",20,2,{"host":"a"}]]
]
```
The first search permits additional metric tags. The second uses recording order to break the timestamp tie.
### Example 2
```text
metrics = [["latency",5,7,{}]]
searches = [["cpu",{},1], ["latency",{},0]]
output = [[], []]
```
One query has no matching name; the other explicitly requests zero results.
Overview: Record metrics and return the newest matches for name-and-tag searches, with explicit tag matching, timestamp ties, duplicates, and result limits.