The Different Ways to Add Parentheses coding problem asks you to take a string representing a mathematical expression (like "2-1-1") and return all possible results that can be obtained by grouping the numbers and operators with parentheses in different ways. For example, "(2-1)-1" results in 0, while "2-(1-1)" results in 2. This problem is about exploring the full combinatorial space of operator precedence.
This is a high-signal question for companies like Microsoft, Meta, and Google. It tests your mastery of Recursion and Divide and Conquer interview patterns. It evaluations whether you can break a large expression into smaller sub-expressions and combine their results. Furthermore, it often leads to a discussion on Memoization, as many sub-problems (sub-expressions) are evaluated multiple times, providing an excellent opportunity to show off optimization skills.
This problem follows the Divide and Conquer pattern. For any given string, you iterate through every character. If you encounter an operator (+, -, *), you split the string into a "left" part and a "right" part. You then recursively find all possible results for the left part and all possible results for the right part. Finally, you combine every result from the left with every result from the right using the current operator.
Suppose the expression is "2*3-4".
[-2, 2].Whenever you encounter a problem that involves "all possible ways" to group or partition data, think about Divide and Conquer. This logic is similar to finding the number of unique Binary Search Trees or generating combinations. Adding a memoization layer (caching results of sub-strings) is almost always expected by top-tier interviewers.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Fibonacci Number | Easy | Solve | |
| Number of Digit One | Hard | Solve | |
| N-th Tribonacci Number | Easy | Solve | |
| Count the Number of Powerful Integers | Hard | Solve | |
| Integer to English Words | Hard | Solve |