Ctrl K

Flip the Circuit Output

Hard
A logic circuit is written as a string formula made of 0, 1, & (AND), | (OR) and parentheses. The formula is well formed: parentheses are balanced, there are no empty parentheses, and operands alternate with operators. Operators have no precedence: parentheses are evaluated first, and inside them operators are applied strictly from left to right. For example, 1|0&0 means (1|0)&0 = 0. One change turns a 0 into a 1 or back, or an & into a | or back. Return the smallest number of changes that makes the whole formula evaluate to the opposite of its current value.
Example 1
formula="0|1&0" → 1

Evaluating left to right: (0|1)&0 = 1&0 = 0. Replace the last 0 with 1: (0|1)&1 = 1. One change is enough.

Example 2
formula="(1&1)|(1&1)" → 2

The value is 1 now. To get 0, either switch off both brackets (one change each) or turn | into & and switch off one bracket. Both ways take 2 changes.

Example 3
formula="1" → 1

Just change the only symbol: 1 → 0.

Constraints
  • 1 ≤ len(formula) ≤ 10⁵
  • formula contains only 0, 1, &, |, (, )
  • the formula is well formed, with no empty ()
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsGrading the Arithmetic Quiz HardLongest Balanced Bracket Stretch HardPlus-Minus Calculator With Brackets HardClear the Marble Row HardSimplify a Letter Polynomial Hard
loading Python…
Input
formula="0|1&0"
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 175 tests on the server, hidden ones included.