Problem · Array

Predicate Expression Tree Evaluator

Learn this problem
MediumMongoDB logoMongoDBFULLTIMEPHONE SCREEN

Problem statement

Evaluate a predicate expression tree against one document. The document is an array of unique [field, value] string pairs. The expression is a nonempty array nodes in topological order, and the last row is the root.

  • ["EQ", field, value] is true when the field exists and its stored string equals value exactly.
  • ["GT", field, value] is true when the field exists and its signed 64-bit integer value is greater than the signed 64-bit integer value.
  • ["AND", childIndex1, ...] is true when every referenced child is true.
  • ["OR", childIndex1, ...] is true when at least one referenced child is true.

Every logical node has at least one child, every child index is smaller than its node index, and all rows are valid. Return the value of the root predicate.

Function

evaluatePredicate(document: String[][], nodes: String[][]) → boolean

Examples

Example 1

document = [["team","search"],["age","31"],["city","Paris"]]nodes = [["EQ","team","search"],["GT","age","25"],["AND","0","1"]]return = true

Both leaf predicates are true, so their AND parent is true.

Example 2

document = [["tier","free"],["visits","4"]]nodes = [["EQ","tier","pro"],["GT","visits","10"],["OR","0","1"]]return = false

Neither leaf predicate is true, so their OR parent is false.

Example 3

document = [["role","admin"],["score","9"]]nodes = [["EQ","role","admin"],["GT","score","20"],["OR","0","1"],["EQ","missing","x"],["AND","2","3"]]return = false

The inner OR is true, but a missing field makes the other child false, so the root AND is false.

Constraints

  • 1 <= document.length, nodes.length <= 200000
  • Document field names are unique.
  • Field names and values contain 1 to 40 printable characters and do not contain the row delimiter used by the runner.
  • Every GT operand is a valid signed 64-bit integer.
  • Each logical node has at least one valid child index smaller than its own index.
  • The last node is the root.
drafts saved locally
public boolean evaluatePredicate(String[][] document, String[][] nodes) {
    // write your code here
}
document[["team","search"],["age","31"],["city","Paris"]]
nodes[["EQ","team","search"],["GT","age","25"],["AND","0","1"]]
expectedtrue
checking account