1708. Flip the Verdict

Hard7.5 points estimatedStackDynamic ProgrammingString

A rule engine evaluates a boolean expression written with the digits 0 and 1, the operators & (and), | (or), ^ (xor), and parentheses. There is no operator precedence: parentheses are evaluated first and everything else is applied strictly from left to right, so "1|0&1" means (1|0)&1.

One operation either flips a single digit (0 to 1 or 1 to 0) or replaces a single operator by one of the other two operators. Parentheses are never changed. Return the minimum number of operations needed to make the final value of expr different from its current value. Process the string with a stack and keep, for every operand, the pair (cost to make it 0, cost to make it 1); combining two operands under an operator tries all three operators and all four value pairs. Aim for O(n) time and O(n) space.

Example 1

Input:
expr = "1&0"
Output:
1
Explanation:

The value is 0; replacing & by | gives 1 | 0 = 1 with a single operation.

Example 2

Input:
expr = "(1|0)^(1&1)"
Output:
1
Explanation:

(1|0) is 1 and (1&1) is 1, so the value is 1 ^ 1 = 0; changing the ^ into | makes it 1 with one operation.

Example 3

Input:
expr = "0"
Output:
1
Explanation:

The single digit 0 becomes 1 by flipping it, which costs 1.

Constraints

1 ≤ expr.length ≤ 105

expr is a valid expression of 0, 1, &, |, ^ and parentheses

No empty parentheses

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…