DSA Stacks

Parsing A Boolean Expression

Stack characters until `)`; pop until `(`, evaluate the operator above, and push the result.

Hard
Time O(n) Space O(n)
LeetCode
4 min read
stack parsing

Problem#

Evaluate a boolean expression containing t (true), f (false), !(expr), &(expr1,expr2,...), and |(expr1,expr2,...). Return true or false.

Examples#

  • "&(|(f))"false
  • "|(f,f,f,t)"true
  • "!(&(f,t))"true

Constraints#

  • 1 <= expression.length <= 2 * 10^4. The expression is always valid.

Approach#

Push every character except ,. On ), pop operands until (, pop the (, pop the operator above, evaluate, push the resulting t/f.

Solution#

Parsing A Boolean Expression
class Solution {
public:
bool parseBoolExpr(string expression) {
stack<char> st;
for (char c : expression) {
if (c == ',') continue;
if (c != ')') { st.push(c); continue; }
int t = 0, f = 0;
while (st.top() != '(') {
char x = st.top(); st.pop();
if (x == 't') ++t;
else ++f;
}
st.pop(); // '('
char op = st.top(); st.pop();
bool val;
if (op == '!') val = (t == 0);
else if (op == '&') val = (f == 0);
else val = (t > 0);
st.push(val ? 't' : 'f');
}
return st.top() == 't';
}
};

Editorial#

For each closing ), the matching ( is one frame down. Between them are the operands. ! always has one operand, so checking t == 0 (i.e., its only operand was f) covers it. & is false iff any operand is false; | is true iff any operand is true.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.