Google questions

Leaf Flip Results

GoogleOnsiteMedium

A boolean expression is stored as a tree written with nested lists. A leaf is a boolean (true or false). An inner node is a list that starts with an operator name: ["AND", left, right], ["OR", left, right], ["XOR", left, right] for two children, or ["NOT", child] for one child. XOR is true when exactly one child is true.

Part 1: Flip each leaf

You are given a boolean expression tree as described above.

For each leaf, from left to right, return the value of the whole expression when that leaf's value is flipped (true becomes false and the reverse) and every other leaf keeps its value. Each leaf is considered independently of the others, and the results are returned in leaf order.

The tree itself may be a single leaf, written as a bare true or false; flipping it gives the opposite value, so the result is a one-element list.

  1. Example 1
    tree
    ["XOR",["OR",false,true],["AND",true,["NOT",true]]]
    Output
    [true,false,true,false]

    Why: The root is true. Flipping the first leaf (false) leaves the OR at true, so the root stays true. Flipping the second leaf (true) makes the OR false and the root false. Flipping the third leaf (true, left child of the AND) leaves the AND false because the NOT beside it is false, so the root stays true. Flipping the last leaf (the one under NOT) makes the NOT true, the AND true and the root false.

Constraints

  • The tree has at most 10^4 nodes (leaves and operator nodes).
  • The tree has depth at most 400.
  • Operator names are exactly AND, OR, XOR and NOT, in capitals.
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question