Toggle Bitwise Expression - Google Top Interview Questions
Problem Statement :
You are given a string s representing a bitwise expression with the following characters: "0", "1", "&", "|", "(", and ")". In one operation, you can: Toggle "0" to "1" Toggle "1" to "0" Change "&" to "|" Change "|" to "&" Return the minimum number of operations required to toggle the value of the expression. Note: the precedence of the operators don't matter, since they'll be wrapped in brackets when necessary. For example, "1&0" and "1&(0&1)" are possible inputs but "1&0&1" will not occur. Constraints 1 ≤ n ≤ 100,000 where n is the length of s Example 1 Input s = "0&(0&(0&0))" Output 2 Explanation The input expression evaluates to 0. To toggle it to 1, we can change the expression to "1|(0&(0&0))". Example 2 Input s = "(1|1)|(1|1)" Output 3 Explanation The input expression evaluates to 1. To toggle it to 0, we can change the expression to "(0&1)&(1|1)". Example 3 Input s = "0&0" Output 2
Solution :
Solution in C++ :
int pairing[1000005];
unordered_map<long long, int> dp;
int force(string& s, int start, int end, int want) {
if (start == end) {
if (s[start] - '0' == want) return 0;
return 1;
}
long long key = (1000000LL * start) + (10 * end) + want;
if (dp.count(key)) return dp[key];
int ret = 1e9;
int lhs[2];
int rhs[2];
if (s[start] == '(' && s[end] == ')' && pairing[start] == end) {
return dp[key] = force(s, start + 1, end - 1, want);
}
if (s[start] == '(') {
int end = pairing[start];
lhs[0] = force(s, start + 1, end - 1, 0);
lhs[1] = force(s, start + 1, end - 1, 1);
start = end + 1;
} else {
int have = s[start++] - '0';
if (have == 0) {
lhs[0] = 0;
lhs[1] = 1;
} else {
lhs[0] = 1;
lhs[1] = 0;
}
}
char op = s[start++];
rhs[0] = force(s, start, end, 0);
rhs[1] = force(s, start, end, 1);
for (int a = 0; a < 2; a++) {
for (int b = 0; b < 2; b++) {
if ((a | b) == want) {
int cost = lhs[a] + rhs[b];
if (op == '&') cost++;
ret = min(ret, cost);
}
if ((a & b) == want) {
int cost = lhs[a] + rhs[b];
if (op == '|') cost++;
ret = min(ret, cost);
}
}
}
dp[key] = ret;
return ret;
}
int eval(string& s, int start, int end) {
assert(start <= end);
if (start == end) {
assert(s[start] == '0' || s[start] == '1');
return s[start] - '0';
}
if (s[start] == '(' && s[end] == ')' && pairing[start] == end) {
return eval(s, start + 1, end - 1);
}
int lhs;
if (s[start] == '(') {
int end = pairing[start];
lhs = eval(s, start + 1, end - 1);
start = end + 1;
} else {
lhs = s[start++] - '0';
}
char op = s[start++];
int rhs = eval(s, start, end);
if (op == '&') {
if (lhs == 0 || rhs == 0) return 0;
return 1;
}
if (op == '|') {
if (lhs == 1 || rhs == 1) return 1;
return 0;
}
assert(false);
}
int solve(string s) {
stack<int> paren;
for (int i = 0; i < s.size(); i++) pairing[i] = -1;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') {
paren.push(i);
} else if (s[i] == ')') {
int lhs = paren.top();
paren.pop();
pairing[lhs] = i;
pairing[i] = lhs;
}
}
int want = eval(s, 0, s.size() - 1);
dp.clear();
return force(s, 0, s.size() - 1, want ^ 1);
}
Solution in Java :
import java.util.*;
class Solution {
private static final class Tree {
private char op = ' ';
private int val = -1;
private Tree left, right;
public Tree(char op) {
this.op = op;
}
public Tree(int val) {
this.val = val;
}
}
private int idx = -1;
public int solve(String s) {
idx = 0;
Stack<Tree> stack = new Stack<>();
build(s, stack);
final Tree ROOT = stack.pop();
int[] res = dfs(ROOT);
return Math.abs(res[0] - res[1]);
}
private int[] dfs(Tree node) {
if (node.val != -1) {
return new int[] {node.val, 1 ^ node.val};
}
int[] left = dfs(node.left);
int[] right = dfs(node.right);
if (node.op == '&') {
int zero = Math.min(left[0], right[0]);
int one = Math.min(left[1] + right[1], 1 + Math.min(left[1], right[1]));
return new int[] {zero, one};
} else {
int zero = Math.min(left[0] + right[0], 1 + Math.min(left[0], right[0]));
int one = Math.min(left[1], right[1]);
return new int[] {zero, one};
}
}
private void build(String s, Stack<Tree> stack) {
if (idx == s.length())
return;
final char ch = s.charAt(idx);
if (ch == '0' || ch == '1') {
idx++;
final Tree node = new Tree(ch - '0');
if (stack.isEmpty())
stack.push(node);
else
stack.peek().right = node;
} else if (ch == '(') {
idx++;
Stack<Tree> tmp = new Stack<>();
build(s, tmp);
if (stack.isEmpty())
stack.push(tmp.pop());
else
stack.peek().right = tmp.pop();
idx++;
} else if (ch == ')') {
return;
} else {
final Tree node = new Tree(ch);
node.left = stack.pop();
stack.push(node);
idx++;
}
build(s, stack);
}
}
Solution in Python :
class Solution:
def solve(self, st):
if len(st) == 1:
return 1
st = "(" + st + ")"
s = []
for x in st:
if x == ")":
# az = min number of edits get to zero on the "a" side
# ao = min number of edits to get to one on the "a" side
az, ao = s.pop()
op = s.pop()
# bz = min number of edits get to zero on the "a" side
# bo = min number of edits to get to one on the "a" side
bz, bo = s.pop()
nz, no = None, None
if op == "|":
# These are just the "standard" way without edits, the new way to get to zero is if both the left and the right are zeroes
nz = az + bz
# We take the cheapest way to get to one by enumerating all the possibilities of a|b ->
# the cost of (a = 0, b = 1), (a = 1, b = 1), (a = 1, b = 0)
no = min(az + bo, ao + bo, ao + bz)
# These are the cost of changing either the left or the right
# another way to get to zero is starting from (a = 0, b = 1), and changing b = 0, with a cost of bo, or (a = 1, b = 0), and changing a = 0, with a cost of ao
nz = min(nz, az + bo + bz, ao + bz + az)
# if a = 0, b = 0, we either change b to 1 (with the cost of bo) or we change a to 1 (with cost of ao)
no = min(no, az + bz + bo, az + bz + ao)
# we can also change the sign - we can get to zero if we change to "and", and it will cost "1" to change the operator
nz = min(nz, min(az + bz, az + bo, ao + bz) + 1)
# we can get to one if we already have ones and change the signs to "and". (Note, this is never going to be true as 1|1 == 1&1, but here for symmetry)
no = min(no, ao + bo + 1)
else:
# Same logic, but for "and"
nz = min(az + bz, az + bo, ao + bz)
no = ao + bo
nz = min(nz, ao + bo + az, ao + bo + bz)
no = min(no, az + bo + ao, ao + bz + bo)
nz = min(nz, az + bz + 1)
no = min(no, min(az + bo, ao + bo, ao + bz) + 1)
s.append((nz, no))
elif x in "01":
if int(x) == 0:
s.append((0, 1))
else:
s.append((1, 0))
elif x not in "(":
s.append(x)
return max(s[0])
View More Similar Problems
Array Pairs
Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .
View Solution →Self Balancing Tree
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ
View Solution →Array and simple queries
Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty
View Solution →Median Updates
The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o
View Solution →Maximum Element
You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each
View Solution →Balanced Brackets
A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra
View Solution →