DSA interview question
You're building a rule-engine for a fraud-detection system at a fintech company. Analysts write boolean rules like "1&0|1" (using 1/0 for true/false and &, |, ^ for AND/OR/XOR) but forget to specify operator precedence or parentheses in legacy rule files migrated from an old system. Since ambiguous expressions could evaluate differently depending on how they're grouped, your task is to compute every possible result obtainable by parenthesizing the expression in all valid ways — so the compliance team can audit whether the rule is ambiguous (multiple distinct outcomes) or safe (all groupings agree).
Given a string expression containing digits 0/1 and operators &, |, ^, return a list of all possible results from evaluating the expression by computing every possible way to parenthesize the operators.
vector<int> diffWaysToEvaluate(string expression);
Input expression | Output | Explanation |
|---|---|---|
| `"1&0 | 1"` | [0, 1] |
| `"0&0&0&1^1 | 0"` | [0, 1] |
"1" | [1] | Single operand, no operators — trivial base case |
"0" | [0] | Single operand |
| `"1^0 | 0 | 1"` |
(Constraints typically: 1 <= expression.length <= 20, expression consists of digits 0/1 and operators &,|,^ only, no spaces, no unary operators)
(Note: since these are boolean 0/1 results, the output is just every distinct {0,1} value achievable — but the classic LeetCode version of this problem uses arithmetic +,-,* and returns ALL results including duplicates, not deduplicated. The boolean variant with &,|,^ is a common interview spin — clarify with interviewer whether to dedupe.)
+, -, * on numbers — the boolean version (&, |, ^ on 0/1) is a common variant/follow-up. They may start with the arithmetic version and pivot to boolean as a follow-up, or vice versa.set? (Arithmetic LC241 keeps duplicates since results are usually distinct numbers; the boolean variant naturally has many duplicates since there are only 2 possible values — confirm whether to dedupe.)&, |, ^? Any operator precedence rules to ignore, or do we treat every split point equally regardless of operator type?On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in