Problem 241

Abstract / Summary

Given a string of numbers and operators, output all possible results from different ways to add parentheses.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
24 lines | 831 bytes | submitted September 8, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (500k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • Math
  • Memoization
  • Recursion
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.63 | σ = 0.91

Complexity Analysis

Time: exponential
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
40 links | 26 authors | 9 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Different Ways to Add Parentheses | Simple Story To Code | Leetcode 241 | codestorywithMIK'
codestorywithMIK 22 mins
Different Ways to Add Parentheses | Simple Story To Code | Leetcode 241 | codestorywithMIK
YouTube video 'Different ways to add parentheses | LeetCode 241| Day 32 | #goProWithBroCoders'
Bro Coders 15 mins
Different ways to add parentheses | LeetCode 241| Day 32 | #goProWithBroCoders
YouTube video 'Different Ways to Add Parentheses | Leetcode 241'
Techdose 23 mins
Different Ways to Add Parentheses | Leetcode 241
YouTube video 'LeetCode 241. [Medium] Different Ways to Add Parentheses'
Francesco Manicardi 4 mins
LeetCode 241. [Medium] Different Ways to Add Parentheses
YouTube video 'Solve 241. Different Ways to Add Parentheses - Java & C++ Solutions | September Challenge'
Mayur Programming Club 13 mins
Solve 241. Different Ways to Add Parentheses - Java & C++ Solutions | September Challenge
YouTube video 'LeetCode 241 | Different Ways to Add Parentheses | Memorization Recursion | Java'
Sleepy Cracker 8 mins
LeetCode 241 | Different Ways to Add Parentheses | Memorization Recursion | Java
YouTube video 'Daily Leetcode #1633: Sep 19, 2024 - 241. Different Ways to Add Parentheses'
Programming Live with Larry 32 mins
Daily Leetcode #1633: Sep 19, 2024 - 241. Different Ways to Add Parentheses
YouTube video '241. Different Ways to Add Parentheses (Leetcode)'
hakunamatasq 11 mins
241. Different Ways to Add Parentheses (Leetcode)
YouTube video 'Different Ways to Add Parentheses DP Tabulation | LeetCode 241 in java | Must do DP problem | DP DSA'
Code Thoughts 23 mins
Different Ways to Add Parentheses DP Tabulation | LeetCode 241 in java | Must do DP problem | DP DSA
YouTube video 'Leetcode Question 241 "Different Ways to Add Parentheses" in Java'
Ghumman Tech 9 mins
Leetcode Question 241 "Different Ways to Add Parentheses" in Java
YouTube video 'Different Ways to Add Parentheses |LeetCode 241 in java | Must do DP problem | Learn DP to recursion'
Code Thoughts 29 mins
Different Ways to Add Parentheses |LeetCode 241 in java | Must do DP problem | Learn DP to recursion
YouTube video '241. Different Ways to Add Parentheses | Strings | Recursion | Leetcode'
Rapid Syntax 14 mins
241. Different Ways to Add Parentheses | Strings | Recursion | Leetcode
YouTube video 'Different Ways to Add Parentheses (Medium), C++, Leetcode'
H William Polenz 226 mins
Different Ways to Add Parentheses (Medium), C++, Leetcode
YouTube video 'LeetCode 241 - Different Ways to Add Parentheses - Java'
Alpha-Code 13 mins
LeetCode 241 - Different Ways to Add Parentheses - Java
YouTube video 'Different Ways to Add Parentheses | Leetcode 241 | Backtracking | Recursion | Java | Developer Coder'
Developer Coder 23 mins
Different Ways to Add Parentheses | Leetcode 241 | Backtracking | Recursion | Java | Developer Coder
YouTube video '241. Different Ways to Add Parentheses | Recursion | LeetCode | Medium | Math'
Leet's Code 15 mins
241. Different Ways to Add Parentheses | Recursion | LeetCode | Medium | Math
YouTube video 'πŸ…ΏπŸ…°πŸ†‚πŸ†‚ Leetcode 241. Different Ways to Add Parentheses'
Pass OR Fail: Coding Journey 36 mins
πŸ…ΏπŸ…°πŸ†‚πŸ†‚ Leetcode 241. Different Ways to Add Parentheses
YouTube video 'Different Ways To Add Parentheses - LeetCode 241 | C++'
Mohammad Senan Ali 17 mins
Different Ways To Add Parentheses - LeetCode 241 | C++
YouTube video 'No Sound Leetcode 241: Different Ways to Add Parentheses'
ExtremeProgrammer 3 mins
No Sound Leetcode 241: Different Ways to Add Parentheses
19 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

1 easy 6 medium
8 solutions   September 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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