Minimum Cost to Change the Final Value of Expression Problem
Description
LeetCode Problem 1896.
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 is1|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 to0.
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.
Example 1:
Input: expression = "1&(0|1)"
Output: 1
Explanation: We can turn "1&(0|1)" into "1&(0&1)" by changing the '|' to a '&' using 1 operation.
The new expression evaluates to 0.
Example 2:
Input: expression = "(0&0)&(0&0&0)"
Output: 3
Explanation: We can turn "(0&0)&(0&0&0)" into "(0|1)|(0&0&0)" using 3 operations.
The new expression evaluates to 1.
Example 3:
Input: expression = "(0|(1|0&1))"
Output: 1
Explanation: We can turn "(0|(1|0&1))" into "(0|(0|0&1))" using 1 operation.
The new expression evaluates to 0.
Constraints:
1 <= expression.length <= 10^5expressiononly contains'1','0','&','|','(', and')'- All parentheses are properly matched.
- There will be no empty parentheses (i.e:
"()"is not a substring ofexpression).
Solution
Approach: Stacks of (value, cost) Pairs
Describe every subexpression by a pair: its value (0 or 1) and the minimum number of operations needed to flip that value. A single digit costs 1 to flip.
Parse the expression with two stacks, one for subexpressions and one for operators. & and | have the same precedence and group from left to right, so a new operator first reduces the pending one, and a closing parenthesis reduces everything back to the matching opening parenthesis.
To combine (v1, c1) and (v2, c2) with &:
- both 1: the result is 1 and flipping costs
min(c1, c2); - both 0: the result is 0; flip both operands (
c1 + c2) or change&to|and flip one operand (1 + min(c1, c2)), whichever is cheaper; - one 0 and one 1: the result is 0; flip the 0 operand or change the operator, whichever is cheaper.
The cases for | are the mirror image. When the expression is fully reduced, the cost on top of the stack is the answer.
Complexity: O(n) time and O(n) space, where n is the length of the expression.
class Solution:
def minOperationsToFlip(self, expression: str) -> int:
def merge(a, b, op):
v1, c1 = a
v2, c2 = b
if op == '&':
val = v1 & v2
if v1 == 1 and v2 == 1:
cost = min(c1, c2)
elif v1 == 0 and v2 == 0:
cost = min(c1 + c2, 1 + min(c1, c2))
else:
cost = min(c1 if v1 == 0 else c2, 1)
else:
val = v1 | v2
if v1 == 0 and v2 == 0:
cost = min(c1, c2)
elif v1 == 1 and v2 == 1:
cost = min(c1 + c2, 1 + min(c1, c2))
else:
cost = min(c1 if v1 == 1 else c2, 1)
return val, cost
nums = []
ops = []
def apply():
b = nums.pop()
a = nums.pop()
nums.append(merge(a, b, ops.pop()))
for c in expression:
if c == '(':
ops.append(c)
elif c in '01':
nums.append((int(c), 1))
elif c in '&|':
while ops and ops[-1] in '&|':
apply()
ops.append(c)
else:
while ops[-1] != '(':
apply()
ops.pop()
while ops:
apply()
return nums[-1][1]