Toy Database — Select a Row by Ordered Keys
Problem statement
A small in-memory database stores records as strings. The first token in each record is its record ID. Every later token is an integer field written as key=value.
Choose one whole record using an ordered list of sort keys. Each sort key is written as key:asc or key:desc.
- Compare two records using the first sort key.
- If the values tie, continue with the next sort key.
- A missing field has value
0. - If the records tie on every requested key, keep the record that appeared earlier in
records.
Return the original record string that comes first under this ordering.
What the interview report shared
The reported exercise grew from selecting a minimum record by one key into minimum-or-maximum selection, comparator reuse, and ordered key/direction priorities. The source allowed collection sorting and treated missing columns as zero.
Function
selectToyDatabaseRow(records: String[], orderBy: String[]) → StringExamples
Example 1
records = ["a|age=5|score=10", "b|score=8", "c|age=5|score=8"]orderBy = ["age:asc", "score:desc"]return = "b|score=8"Record b is missing age, so its value for that key is 0. It therefore comes before the two records whose age is 5.
Example 2
records = ["x|team=2|score=7", "y|team=2|score=9", "z|team=1|score=100"]orderBy = ["team:desc", "score:desc"]return = "y|team=2|score=9"The two records with team=2 come first under descending team order. Their team values tie, so descending score selects record y.
Constraints
1 <= records.length <= 10^5.- Every record begins with a unique non-empty ID followed by zero or more
key=valuetokens separated by|. - Keys contain lowercase English letters; values are 32-bit signed integers.
1 <= orderBy.length <= 20, and every entry ends with:ascor:desc.- For this exercise, assume a missing field has value
0and a complete comparison tie keeps the earlier input record.