Minimum Cost to Change the Final Value of Expression - Problem
Minimum Cost to Change the Final Value of Expression
You are given a valid boolean expression as a string consisting of:
•
•
•
•
Important: Unlike typical boolean expressions, operators have equal precedence and are evaluated left-to-right (after handling parentheses).
Your goal is to find the minimum number of operations needed to flip the final result of the expression. You can perform these operations:
1. Turn
2. Turn
Example: If
• Current evaluation:
• We want to change it to evaluate to
• Return the minimum cost to achieve this flip
You are given a valid boolean expression as a string consisting of:
•
'1' and '0' (boolean values)•
'&' (bitwise AND operator)•
'|' (bitwise OR operator)•
'(' and ')' (parentheses for grouping)Important: Unlike typical boolean expressions, operators have equal precedence and are evaluated left-to-right (after handling parentheses).
Your goal is to find the minimum number of operations needed to flip the final result of the expression. You can perform these operations:
1. Turn
'1' → '0' or '0' → '1'2. Turn
'&' → '|' or '|' → '&'Example: If
expression = "1|1|(0&0)&1"• Current evaluation:
1|1|0&1 = 1|0&1 = 1&1 = 1• We want to change it to evaluate to
0• Return the minimum cost to achieve this flip
Input & Output
example_1.py — Simple OR Expression
$
Input:
expression = "1|1|(0&0)&1"
›
Output:
1
💡 Note:
The expression evaluates as: 1|1|0&1 = 1|0&1 = 1&1 = 1. To make it evaluate to 0, we can change the last '1' to '0': "1|1|(0&0)&0" → 1|1|0&0 = 1|0&0 = 1&0 = 0. Cost: 1 operation.
example_2.py — Parentheses Expression
$
Input:
expression = "(0&0)&1"
›
Output:
1
💡 Note:
The expression evaluates as: (0&0)&1 = 0&1 = 0. To make it evaluate to 1, we can change the '&' to '|': "(0&0)|1" → 0|1 = 1. Cost: 1 operation.
example_3.py — Single Digit
$
Input:
expression = "0"
›
Output:
1
💡 Note:
The expression evaluates to 0. To make it evaluate to 1, we need to change '0' to '1'. Cost: 1 operation.
Constraints
- 1 ≤ expression.length ≤ 105
-
expression consists of
'1','0','&','|','(', and')' - All parentheses are properly matched
- The given expression is guaranteed to be valid
- No operator precedence - evaluate left-to-right after parentheses
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code