Magicsheet logo

Minimum Cost to Change the Final Value of Expression

Hard
25%
Updated 8/1/2025

Minimum Cost to Change the Final Value of Expression

What is this problem about?

The Minimum Cost to Change the Final Value of Expression problem gives you a boolean expression involving 0, 1, & (AND), and | (OR), along with parentheses. You need to find the minimum number of bit flips (changing 0 to 1 or 1 to 0) or operator flips (changing & to | or | to &) required to change the final evaluation of the entire expression.

Why is this asked in interviews?

This is a high-level Minimum Cost to Change Expression interview question at Google. It combines Expression Parsing (using a stack) with Dynamic Programming. It tests whether a candidate can manage complex states (the value of an expression and the cost to flip it) through a tree-like recursive structure.

Algorithmic pattern used

The Stack-based Expression Parsing with DP interview pattern is used here.

  1. Parse the expression using two stacks (one for values, one for operators).
  2. Instead of just storing the result (0 or 1), store a pair: (value, cost_to_flip).
  3. For an operation like A | B:
    • If A=0, B=0, result is 0. Cost to flip to 1 is min(costA, costB). (No, actually min(costA, costB) because changing either to 1 makes 0|1=1).
    • If A=1, B=1, result is 1. Cost to flip to 0 is 1 + min(costA, costB)? No, the rules are specific to boolean logic.
  4. You derive the flip cost for each operator (&, |) based on the flip costs of its operands.

Example explanation

Expression: (0&1). Value is 0.

  1. 0 has cost 1 to become 1.
  2. 1 has cost 1 to become 0.
  3. To flip (0&1) to 1:
    • Change & to |: (0|1) = 1. (Cost 1).
    • Change 0 to 1: (1&1) = 1. (Cost 1).
  4. Minimum cost is 1.

Common mistakes candidates make

  • Only considering bit flips: Forgetting that you can also flip the operators (& to |), which is often cheaper.
  • Incorrect DP transitions: Getting the boolean logic wrong for the flip costs (e.g., thinking 1|1 needs two flips to become 0).
  • Parsing errors: Not handling nested parentheses or operator precedence correctly.

Interview preparation tip

When an expression problem asks for an "optimal" change, you can't just evaluate the expression. You must evaluate the cost function alongside the values. Think of it as "evaluating the expression in the domain of (value, flip_cost)."

Similar Questions