Distribute and Expand Algebraic Products
StringsAuto-graded · 27 test casesLast updated
Tests recursive parsing, the distributive property of multiplication over addition, and constructing expanded expressions from nested operations.
You are given a string representing an algebraic expression consisting of lowercase letters, the operators + and *, and parentheses ( and ). Your task is to fully expand the expression by applying the distributive property of multiplication over addition, then return the result as a sum of product terms joined by +.
Rules
- A product term is formed by multiplying factors together. When multiplying two letters or groups, concatenate them (e.g.,
a * bbecomesab). - The distributive property means
x * (y + z)expands toxy + xz, and(a + b) * (c + d)expands toac + ad + bc + bd. - Multiplication binds more tightly than addition. Within products, multiplication is left-associative.
- Consecutive lowercase letters without operators between them are implicitly multiplied (e.g.,
abcisa * b * c). - The output should list all product terms in the order they naturally arise from left-to-right expansion, joined by
+. - Do not simplify, reorder, or combine like terms. Each distinct product from the expansion appears separately in the output.
Constraints
1 ≤ len(expression) ≤ 1000- The expression contains only lowercase English letters,
+,*,(, and). - The input is always a well-formed algebraic expression.
- Parentheses may be nested to any depth.
Examples
Example 1
Input: distribute_expression('(a+b)*(c+d)')
Output: 'ac+ad+bc+bd'
Example 2
Input: distribute_expression('a+b*c*(d+e+f)+k+m*(g+h)+i')
Output: 'a+bcd+bce+bcf+k+mg+mh+i'
Example 3
Input: distribute_expression('a*(b+c)')
Output: 'ab+ac'
Example 4
Input: distribute_expression('(a+b+c)')
Output: 'a+b+c'
Hints
Hint 1
Think about how to parse the expression recursively: an expression is a sum of products, and each product is a sequence of factors (letters or parenthesized sub-expressions).
Hint 2
When you multiply two lists of terms together, the result is the Cartesian product: every term from the first list concatenated with every term from the second list.
Hint 3
A recursive descent parser with separate functions for sums, products, and atoms (letters or parenthesized expressions) naturally handles operator precedence and nesting.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to use recursive descent parsing to respect operator precedence: addition has lower precedence than multiplication, and parentheses override precedence. We represent intermediate results as lists of product terms (strings), then combine them according to the operators.
The parser has three mutually recursive functions:
-
parse_sum: Parses a sum of one or more products separated by
+. It callsparse_productfor the first term, then extends the list with additional products after each+sign. -
parse_product: Parses a product of one or more atoms (factors) separated by
*. It starts with the first atom, then for each subsequent*, it takes the Cartesian product: every term from the left list concatenated with every term from the right atom's list. -
parse_atom: Parses a single factor, which is either a sequence of consecutive lowercase letters or a parenthesized sub-expression. For parentheses, it recursively calls
parse_sumto handle the contents.
The distributive property emerges naturally from the Cartesian product step: when we multiply (a + b) by (c + d), we get lists ["a", "b"] and ["c", "d"], and their Cartesian product is ["ac", "ad", "bc", "bd"].
Finally, we join all the resulting terms with + to produce the output string.
Why It Works
- Operator precedence: By having
parse_sumcallparse_product, andparse_productcallparse_atom, we naturally enforce that multiplication binds tighter than addition. - Cartesian product implements distribution: The list comprehension
[left + part for left in terms for part in right]expands every combination, which is exactly what the distributive law requires. - Parsing handles nesting: Recursive calls inside
parse_atommean arbitrarily nested parentheses are correctly processed from the inside out.
Complexity
- Time: O(n · T), where n is the input length and T is the number of output terms. In the worst case, deeply nested multiplications can produce exponentially many terms (e.g.,
(a+b)*(c+d)*(e+f)*...yields 2^k terms for k groups), and each term requires scanning input positions. - Space: O(n + T) for the recursion stack (depth proportional to nesting) and the lists of intermediate terms. The output itself is O(T · m), where m is the average term length.
Solution Code
def distribute_expression(expression):
i = 0
def parse_sum():
nonlocal i
terms = parse_product()
while i < len(expression) and expression[i] == '+':
i += 1
terms.extend(parse_product())
return terms
def parse_product():
nonlocal i
terms = parse_atom()
while i < len(expression) and expression[i] == '*':
i += 1
right = parse_atom()
terms = [left + part for left in terms for part in right]
return terms
def parse_atom():
nonlocal i
if expression[i] == '(':
i += 1
terms = parse_sum()
i += 1
return terms
start = i
while i < len(expression) and 'a' <= expression[i] <= 'z':
i += 1
return [expression[start:i]]
return '+'.join(parse_sum())