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.
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.
The Stack-based Expression Parsing with DP interview pattern is used here.
(value, cost_to_flip).A | B:
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).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.&, |) based on the flip costs of its operands.Expression: (0&1). Value is 0.
0 has cost 1 to become 1.1 has cost 1 to become 0.(0&1) to 1:
& to |: (0|1) = 1. (Cost 1).0 to 1: (1&1) = 1. (Cost 1).& to |), which is often cheaper.1|1 needs two flips to become 0).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)."
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count the Number of Powerful Integers | Hard | Solve | |
| Longest Valid Parentheses | Hard | Solve | |
| Count of Integers | Hard | Solve | |
| Number of Ways to Divide a Long Corridor | Hard | Solve | |
| Minimum Deletions to Make String Balanced | Medium | Solve |