Python 0241.py
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
@cache
def deeper(s):
if s.isnumeric():
return [ int(s) ]
result = []
for i in range(len(s)):
if s[i] in [ "+", "-", "*"]:
left = deeper(s[:i])
right = deeper(s[i+1:])
for l in left:
for r in right:
if s[i] == "+":
result.append(l + r)
elif s[i] == "-":
result.append(l - r)
elif s[i] == "*":
result.append(l * r)
return result
return deeper(expression)
Difficulty
and has an acceptance rate of about 73% (500k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- Math
- Memoization
- Recursion
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes all possible results from evaluating an arithmetic expression that contains the binary operators +, -, and *. It treats the expression as a sequence of numbers and operators and explores every way of inserting parentheses, effectively generating every distinct binary tree representation of the computation. The core logic is encapsulated in a recursive helper function that is memoized, allowing repeated sub-expressions to be evaluated only once.
Core Logic
The entry point diffWaysToCompute receives the raw expression string and immediately invokes the nested function deeper. The helper is defined with the @cache decorator, which automatically stores the result list for each distinct substring it processes. This memoization is crucial because the same substring can appear many times in different recursive branches.
@cache
def deeper(s):
...
Numeric Base Case
When the substring consists solely of digits, the function identifies it as a leaf node of the computation tree. The str.isnumeric() test guarantees that no operators are present, and the integer conversion yields the sole possible value for that sub-expression.
if s.isnumeric():
return [int(s)]
Splitting on Operators
For non-numeric substrings, the function iterates over each character position. Whenever it encounters one of the three supported operators, it partitions the string into a left part and a right part. Recursive calls compute all possible outcomes for each side.
result = []
for i in range(len(s)):
if s[i] in ["+", "-", "*"]:
left = deeper(s[:i])
right = deeper(s[i+1:])
...
Combining Sub-Results
The nested loops iterate over every combination of a left result l and a right result r. Depending on the operator at the split point, the appropriate arithmetic operation is performed, and the outcome is appended to the result list.
for l in left:
for r in right:
if s[i] == "+":
result.append(l + r)
elif s[i] == "-":
result.append(l - r)
elif s[i] == "*":
result.append(l * r)
After processing all operator positions, the accumulated list of possible values is returned to the caller.
return result
Finally, the outer method returns the list produced for the full expression.
return deeper(expression)
Edge Cases Handled
The implementation gracefully handles expressions that consist of a single integer without any operators. The numeric base case returns a list containing that integer, ensuring the caller receives a correctly typed result.
When an operator appears at the very beginning or end of the string, the loop never treats it as a split point because the corresponding left or right substring would be empty, and s.isnumeric() would be false. Consequently, such malformed inputs simply yield an empty result list, which aligns with the expectation that only well-formed expressions produce values.
Multiple consecutive operators are not a concern because the numeric check prevents recursion on non-numeric substrings that lack a valid split point, effectively filtering out invalid configurations.
The memoization mechanism also implicitly handles repeated sub-expressions, such as "2*3*2" where the substring "2*3" appears in more than one recursive branch. The cached result prevents redundant computation and guarantees consistent output for identical inputs.
Performance Optimizations
The most significant optimization is the use of the @cache decorator on the recursive helper. By storing the list of results for each distinct substring, the algorithm avoids exponential recomputation of identical sub-problems. This dramatically reduces the number of recursive calls, especially for expressions with repeated patterns or overlapping sub-expressions.
Another subtle optimization is the early exit for numeric substrings. Recognizing a leaf node without further recursion eliminates unnecessary loop iterations and function calls for the simplest cases.
The algorithm builds the result list incrementally, appending each computed value as soon as it is produced. This avoids the overhead of intermediate data structures and keeps memory usage focused on the final set of outcomes for each sub-expression.
Overall, the combination of memoization, early base-case detection, and direct list accumulation yields an efficient exploration of the exponential space of parenthesizations while keeping the actual work proportional to the number of unique sub-expressions.
ELI5 - Simplified Explanation
Imagine you have a long string of numbers and math symbols like plus, minus, and times signs. This code acts like a curious explorer deciding which part of the math problem to solve first. Because there are different ways to group the numbers using parentheses, the code tries every possible way to combine them.
The code starts by looking for a math symbol. When it finds one, it splits the problem into a left side and a right side. It then asks its helpers to solve those smaller pieces. Each helper does the same thing until they reach a simple number. Once the pieces are just numbers, the code performs the math for that specific part. It gathers all the different results it finds because there might be several ways to calculate the final answer depending on which order you pick. By saving the answers to parts it has already solved, the code makes sure it does not have to do the same work twice, which helps it finish the job much faster.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | C# | Go | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Java | Python | |||||||
| github | aylei | Rust | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| gaosq0604 | Python | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lennylxx | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| gaosq0604 | Python | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lennylxx | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 95: Unique Binary Search Trees II
- problem 224: Basic Calculator
- problem 282: Expression Add Operators
- problem 2019: The Score of Students Solving Math Expression
- problem 2232: Minimize Result by Adding Parentheses to Expression
Solved On The Same Day
- problem 401: Binary Watch
- problem 227: Basic Calculator II
- problem 284: Peeking Iterator
- problem 299: Bulls and Cows
- problem 365: Water and Jug Problem
- problem 375: Guess Number Higher or Lower II
- problem 376: Wiggle Subsequence
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality