Parsing A Boolean Expression

Hard · Stack & Strings · String · Stack · Recursion

Problem

You are given a string expression that describes a boolean expression in one of these forms:

The expression is always valid. Evaluate it and return the result as a boolean.

Examples

Input: expression = "&(t,|(f,t),!(t))"
Output: false

The parts evaluate to t, t and f, and an AND with any false part is false.

Input: expression = "|(f,!(f))"
Output: true

!(f) is true, so the OR is true.

Input: expression = "&(t,!(f),t)"
Output: true

All three parts are true.

Constraints

Approaches

Follow-up

A recursive-descent parser (one function that reads an expression and returns its value and where it ended) is the most natural way to write this, but nesting can be about 5,000 levels deep here, past Python's default recursion limit. The explicit stack has no such limit. Could you also short-circuit, skipping the rest of an AND as soon as you see an f? Only by skipping to the matching ), which still means reading those characters.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…