OpenAI questions

In-Memory Table Queries

OpenAIPhone screenMedium

Build an in-memory table MemoryDB that stores records and answers queries over them. A record is a dictionary with string field names and values that are integers or strings. Different records may have different fields; there is no declared schema.

A condition is a list [field, op, value] where op is one of "=", "!=", "<", ">", "<=", ">=". A row satisfies a condition only if it has field, its value for field has the same type as value (both integers or both strings), and the comparison holds. Strings compare in dictionary order. A row that lacks the field, or holds a value of the other type, fails the condition for every operator, including "!=". A list of conditions is joined by AND; an empty list is satisfied by every row.

Each test drives one MemoryDB() instance through a sequence of calls and checks every return value.

Part 1: Insert, filter and project

Implement:

  • insert(record) adds a copy of record to the table and returns None.
  • select(columns, where) returns the rows that satisfy every condition in where, in insertion order. If columns is empty, each result is a copy of the full record. Otherwise each result is a dictionary with exactly the keys in columns, in that order, where a column the row does not have is None.
  1. Example 1
    init
    []
    operations
    [["insert",[{"id":1,"age":30,"name":"Alice"}]],["insert",[{"id":2,"age":25,"name":"Bob"}]],["select",[[],[["age",">",25]]]],["select",[["name"],[["age",">=",25]]]],["select",[[],[]]]]
    Output
    [null,null,[{"id":1,"age":30,"name":"Alice"}],[{"name":"Alice"},{"name":"Bob"}],[{"id":1,"age":30,"name":"Alice"},{"id":2,"age":25,"name":"Bob"}]]

    Why: Alice is 30 and Bob is 25, so only Alice has age > 25. The second query keeps both rows (age >= 25) but returns only the name column. An empty condition list matches every row and returns full records.

Constraints

  • 1 <= len(operations) <= 10^3
  • 0 <= len(record) <= 10
  • 0 <= len(where) <= 5
  • 1 <= len(field) <= 10 for every field name in record and where
  • -10^9 <= value <= 10^9 for every integer in record and where
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
In-Memory Table Queries: OpenAI interview question | LoopCoach