FastPrepToy Database — Select a Row by Ordered Keys

Toy Database — Select a Row by Ordered Keys

Stripe logoStripe● MediumINTERNPHONE SCREEN
Learn

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.

  1. Compare two records using the first sort key.
  2. If the values tie, continue with the next sort key.
  3. A missing field has value 0.
  4. 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[]) → String

Examples

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=value tokens separated by |.
  • Keys contain lowercase English letters; values are 32-bit signed integers.
  • 1 <= orderBy.length <= 20, and every entry ends with :asc or :desc.
  • For this exercise, assume a missing field has value 0 and a complete comparison tie keeps the earlier input record.

More Stripe problems

See Stripe hiring insights
public String selectToyDatabaseRow(String[] records, String[] orderBy) {
    // write your code here
}
records["a|age=5|score=10", "b|score=8", "c|age=5|score=8"]
orderBy["age:asc", "score:desc"]
expected"b|score=8"
Checking account…