Boolean String Value

Given a string consisting of only 0, 1, A, B, C where
A = AND
B = OR
C = XOR
Calculate the value of the string assuming no order of precedence and evaluation is done from left to right.

Examples:
Input :
1A0B1

Output : 1
1 AND 0 OR 1 = 1

Input :
2
1C1B1B0A0
1A0B1

Output :
0
1

💡Strategies for Solving This Problem

Expression Parsing and Evaluation

This is about parsing and evaluating boolean expressions from strings. Common at Google and Meta. Got a similar problem at Google in 2024.

The Problem

Given a string like "true AND false OR true", evaluate it to boolean result.

Complexity Levels

Level 1: Simple infix, no parentheses
Level 2: With parentheses
Level 3: With operator precedence (AND before OR)
Level 4: With NOT operator

Approach 1: Simple Left-to-Right

If no parentheses or precedence, evaluate left to right. Split by operators, process sequentially.

Approach 2: Recursive Descent

For precedence and parentheses, use recursive parsing:

  • Parse expression
  • Handle OR (lowest precedence)
  • Handle AND (higher precedence)
  • Handle NOT (highest precedence)
  • Handle parentheses

Approach 3: Shunting Yard + Stack Evaluation

Convert infix to postfix (Reverse Polish Notation), then evaluate with stack. More complex but handles all cases.

Key Insight

Operator precedence matters! "true OR false AND false" depends on precedence:

  • Left-to-right: (true OR false) AND false = false
  • AND first: true OR (false AND false) = true

Standard: AND has higher precedence than OR.

At Google

Started with simple tokenization and left-to-right evaluation. Interviewer added parentheses, then asked about precedence. Had to rebuild with recursive parser.

Scroll to Top