Minimum Cost to Change the Final Value of Expression - Problem

You are given a valid boolean expression as a string expression consisting of the characters '1', '0', '&' (bitwise AND operator), '|' (bitwise OR operator), '(', and ')'.

For example, "()1|1" and "(1)&()" are not valid while "1", "(((1)))|(0)", and "1|(0&(1))" are valid expressions.

Return the minimum cost to change the final value of the expression.

For example, if expression = "1|1|(0&0)&1", its value is 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new expression evaluates to 0.

The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows:

  • Turn a '1' into a '0'.
  • Turn a '0' into a '1'.
  • Turn a '&' into a '|'.
  • Turn a '|' into a '&'.

Note: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.

Input & Output

Example 1 — Basic Expression
$ Input: expression = "1|1|(0&0)&1"
Output: 1
💡 Note: Original evaluates to 1 (since 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1). We can change the first '1' to '0' to get 0|1|(0&0)&1 = 0, with cost 1.
Example 2 — Simple AND
$ Input: expression = "(1)&(0)"
Output: 1
💡 Note: Original evaluates to 0 (since 1&0 = 0). We can change '0' to '1' to get 1&1 = 1, with cost 1.
Example 3 — Single Operand
$ Input: expression = "0"
Output: 1
💡 Note: Original evaluates to 0. We need to change it to 1, so we flip the '0' to '1' with cost 1.

Constraints

  • 1 ≤ expression.length ≤ 105
  • expression consists of '1', '0', '&', '|', '(', and ')'
  • expression is a valid boolean expression

Visualization

Tap to expand
INPUTALGORITHMRESULTExpression: "1|1|(0&0)&1"1|1|(0&0)&1Original evaluates to: 1Target: flip to 0&|1101Parse Expression Tree2Calculate DP Costs3Consider Operator Changes4Return Min CostCost Table Example:Node: cost[0], cost[1]Root: 1, 0Minimum Cost: 1One operation neededPossible solutions:Change first 1 → 00|1|(0&0)&1 = 0Or change & → |1|1|(0&0)|1 = 01Key Insight:Track minimum cost to make each subexpression evaluate to both 0 and 1, considering both operand flips and operator changes.TutorialsPoint - Minimum Cost Expression Flip | Memoization DP
Asked in
Google 15 Microsoft 12 Amazon 8 Facebook 6
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen