Expand Expressions into Sum-of-Products Form
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given an algebraic formula expression written without whitespace using lowercase English letters ('a'–'z'), '+', '*', '(', and ')'. Rewrite the formula as a flat sum of variable strings joined solely by '+', eliminating all parentheses and multiplication operators through repeated distribution.
Every expression obeys these algebraic and ordering conventions:
- Explicit and implicit products: Multiplication is written either with
'*'or by placing factors directly next to one another (for instance,pq,p(q+r), or(p+q)(r+s)). Multiplication takes precedence over'+'. - Non-commutative factor order: Inside each expanded product term, keep variables in the exact sequence they were encountered from left to right (for example,
q*pbecomesqp, neverpq). - Left-to-right distribution order: When multiplying
(L_1 + L_2 + ...) * (R_1 + R_2 + ...), pairL_1with everyR_jin order before advancing toL_2, and so forth. - No term combining: Keep identical product terms separate rather than introducing numerical coefficients or removing duplicates (for example,
(x+x)*ybecomesxy+xy).
In an interview setting, this problem builds in two stages:
- Restricted chains: When
'+'occurs solely inside flat, unnested parenthesized groups, every expanded product can be emitted usingO(1)auxiliary working variables beyond the output buffer (no stack required). - Arbitrary nesting (judge target): Implement
expand_expression(expression: str) -> strfor any valid input where'+'may appear at any level and parentheses may nest to arbitrary depth, usingO(n)parser state beyond the generated terms.
Examples
Example 1
Input: expression = "(x+y+z)*(u+v)"
Output: "xu+xv+yu+yv+zu+zv"
Hold x fixed while stepping through u and v (xu, xv), then hold y fixed (yu, yv), and finally hold z fixed (zu, zv).
Example 2
Input: expression = "k*(m+n)*p*(q+r)"
Output: "kmpq+kmpr+knpq+knpr"
Fixed factors k and p stay in their left-to-right slots while (m+n) and (q+r) advance like a two-wheel counter: (m, q), (m, r), (n, q), (n, r).
Example 3
Input: expression = "p+q*r*(s+t)+u*(v+w+x)+y"
Output: "p+qrs+qrt+uv+uw+ux+y"
Top-level '+' signs split the input into four independent summands: p, q*r*(s+t) (qrs+qrt), u*(v+w+x) (uv+uw+ux), and y.
Example 4
Input: expression = "w*(x+(y+z)*u)"
Output: "wx+wyu+wzu"
Inside the outer parentheses, (y+z)*u expands first to yu+zu, producing x+yu+zu. Distributing w on the left then yields wx+wyu+wzu.
Constraints
1 <= len(expression) <= 200expressioncontains only lowercase ASCII letters ('a'–'z'),'+','*','(', and')'.- All parentheses are balanced and enclose non-empty sub-expressions;
'+'and'*'always appear as binary operators between valid factors. - The fully expanded result contains at most
10^5characters.
Step-by-step walkthrough
Understand the exact expansion rules
We are given a valid formula made of lowercase single-letter variables,
+,*,(, and), with no spaces. Our goal is to rewrite it using only+by applying the distributive property — the rulex * (y + z) = xy + xz— until all parentheses and multiplications disappear.Four formatting rules completely pin down the answer:
- Concatenation means multiplication: Both
p*qandpq(orp(q+r)and(p+q)(r+s)) represent multiplication, and output products are written without*(pq). - Keep variable order inside every term: Multiplication is not sorted alphabetically —
q*pmust stayqp, neverpq. - Left-to-right expansion order: In
(x+y+z)*(u+v), we holdxfixed while stepping throughu, v, then holdyfixed while stepping throughu, v, and finally holdzfixed, givingxu+xv+yu+yv+zu+zv. - Never merge duplicate terms:
(x+x)*yexpands toxy+xy, not2xyorxy.
- Concatenation means multiplication: Both
Stage 1: why flat products act like a car odometer
When
+appears only inside non-nested parentheses, such as Example 2 (k*(m+n)*p*(q+r)), every factor is either fixed letters (k,p) or a parenthesized menu of choices ((m+n)has2choices,(q+r)has2choices).Picking one option from each group in left-to-right order works just like a car odometer, where the rightmost wheel spins fastest and the leftmost wheel spins slowest:
Expression: k * (m + n) * p * (q + r) Group sizes: 2 x 2 = 4 total terms Counter t Wheel digits (group 1, group 2) Chosen letters Output term --------- ------------------------------- -------------- ----------- 0 (0, 0) k, m, p, q kmpq 1 (0, 1) k, m, p, r kmpr 2 (1, 0) k, n, p, q knpq 3 (1, 1) k, n, p, r knprBecause term index
tencodes which option to pick from each(...)group via integer division and remainder, Stage 1 can emit all terms usingO(1)extra working variables (just loop indices and counters, with no stack at all). However, once+can appear outside parentheses (p+q*r*(s+t)) or groups nest inside groups (w*(x+(y+z)*u)), a single flat odometer no longer fits — we need the general stack model.Represent every sub-expression as a list of terms
In the general case, any sub-expression expands to an ordered list of product strings, such as
["xu", "xv", "yu", "yv"]. Under this representation:- Addition (
+) simply concatenates two lists of terms:["p"] + ["qrs", "qrt"]->["p", "qrs", "qrt"]. - Multiplication (
*or concatenation) pairs every term on the left with every term on the right, keepingleft_termsas the outer loop so left choices change slowest. - Empty starting product (
[""]): What should an empty product be before its first letter arrives? It must be[""]— a list containing one empty string — NOT[]! Just as1is the multiplicative identity in arithmetic (1 * x = x) while0wipes everything out (0 * x = 0),distribute([""], ["p"])gives["" + "p"] = ["p"], whereasdistribute([], ["p"])would give[]!
from typing import List def distribute(left_terms: List[str], right_terms: List[str]) -> List[str]: """Multiply two expanded sums by pairing every left term with every right term.""" expanded: List[str] = [] for left_term in left_terms: for right_term in right_terms: expanded.append(left_term + right_term) return expanded- Addition (
Handle one flat level of `+` and `*` without parentheses
Before adding parentheses, trace how operator precedence (
*binds tighter than+) works on a flat string likep+q*ras we scan left to right with two variables:sum_terms:List[str]of completed+-separated terms finished earlier on this level (starts at[]).current_product:List[str]of terms in the multiplication chain we are currently building (starts at[""]).
Each character updates those two lists:
- Letter
ch: extends the active multiplication chain:current_product = distribute(current_product, [ch]). '*': does nothing at all! Bothq*rand implicitqrsimply multiplycurrent_productwhenrarrives.'+': closes the active multiplication chain: appendcurrent_productintosum_terms, then resetcurrent_product = [""]to begin the next product after+.
Scan "p+q*r": start -> sum_terms = [], current_product = [""] 'p' -> sum_terms = [], current_product = ["p"] '+' -> sum_terms = ["p"], current_product = [""] 'q' -> sum_terms = ["p"], current_product = ["q"] '*' -> (no change) 'r' -> sum_terms = ["p"], current_product = ["qr"] end -> sum_terms + current_product = ["p", "qr"] -> "p+qr"Add a stack to handle nested parentheses
Now suppose we hit
'('in the middle of a product, such asq*r*(s+t). We cannot multiplycurrent_product(["qr"]) yet because we do not know all the terms inside(s+t)until we reach')'.A stack (a last-in, first-out list of saved frames) solves nesting to any depth:
- On
'(': push(sum_terms, current_product)ontostackto pause the outer level, then resetsum_terms = []andcurrent_product = [""]for the new inner group. - On
')': the inner group is now finished asgroup_terms = sum_terms + current_product. Pop the paused outer(sum_terms, current_product)fromstack, and multiply the outer product by the group:current_product = distribute(current_product, group_terms).
from typing import List, Tuple def distribute(left_terms: List[str], right_terms: List[str]) -> List[str]: expanded: List[str] = [] for left_term in left_terms: for right_term in right_terms: expanded.append(left_term + right_term) return expanded def expand_expression(expression: str) -> str: stack: List[Tuple[List[str], List[str]]] = [] sum_terms: List[str] = [] current_product: List[str] = [""] for ch in expression: if ch.isalpha(): current_product = distribute(current_product, [ch]) elif ch == "(": stack.append((sum_terms, current_product)) sum_terms = [] current_product = [""] elif ch == ")": group_terms = sum_terms + current_product sum_terms, current_product = stack.pop() current_product = distribute(current_product, group_terms) elif ch == "+": sum_terms.extend(current_product) current_product = [""] all_terms = sum_terms + current_product return "+".join(all_terms)- On
Trace Example 3 and nested Example 4
First trace Example 3,
p+q*r*(s+t)+u*(v+w+x)+y:Read stack (top) sum_terms current_product ---------- ----------------- ------------------------- ----------------- p [] [] ["p"] + [] ["p"] [""] q*r* [] ["p"] ["qr"] ( [(["p"], ["qr"])] [] [""] s+t [(["p"], ["qr"])] ["s"] ["t"] ) [] ["p"] ["qrs","qrt"] + [] ["p","qrs","qrt"] [""] u*(v+w+x) [] ["p","qrs","qrt"] ["uv","uw","ux"] +y [] [...,"uv","uw","ux"] ["y"] end -> "p+qrs+qrt+uv+uw+ux+y"Now trace nested Example 4,
w*(x+(y+z)*u):Read stack sum_terms current_product ----- --------------------------------- ---------- ------------------ w* [] [] ["w"] ( [([], ["w"])] [] [""] x+ [([], ["w"])] ["x"] [""] ( [([], ["w"]), (["x"], [""])] [] [""] y+z [([], ["w"]), (["x"], [""])] ["y"] ["z"] ) [([], ["w"])] ["x"] ["y", "z"] *u [([], ["w"])] ["x"] ["yu", "zu"] ) [] [] ["wx","wyu","wzu"] end -> "wx+wyu+wzu"Complete solution
Here is the full, self-contained implementation with explanatory comments:
from typing import Any, Dict, List, Optional, Set, Tuple def distribute(left_terms: List[str], right_terms: List[str]) -> List[str]: """Multiply two expanded sums by pairing every left term with every right term. Iterating `left_terms` in the outer loop keeps left terms changing slowest, producing left-to-right expansion order: (x+y)*(u+v) -> xu, xv, yu, yv. """ expanded: List[str] = [] for left_term in left_terms: for right_term in right_terms: expanded.append(left_term + right_term) return expanded def expand_expression(expression: str) -> str: # stack: list of saved (sum_terms, current_product) frames, one per open '(' stack: List[Tuple[List[str], List[str]]] = [] # sum_terms: completed '+'-separated product terms at the current parenthesis level sum_terms: List[str] = [] # current_product: expanded terms of the active multiplication chain. # Starts as [""] (one empty string, acting like 1 in multiplication) rather than [] # (which would act like 0 and wipe out everything multiplied into it). current_product: List[str] = [""] for ch in expression: if ch.isalpha(): # Append this variable to every term in the active product chain. current_product = distribute(current_product, [ch]) elif ch == "(": # Pause the outer sum and product on the stack and start a fresh inner level. stack.append((sum_terms, current_product)) sum_terms = [] current_product = [""] elif ch == ")": # Flush the inner level into one list of terms, restore the outer level, # and distribute the outer product across the closed parenthesized group. group_terms = sum_terms + current_product sum_terms, current_product = stack.pop() current_product = distribute(current_product, group_terms) elif ch == "+": # Multiplication binds tighter than '+', so '+' finishes `current_product` # and resets it to [""] for the next product segment. sum_terms.extend(current_product) current_product = [""] # Explicit '*' needs no action: both 'a*b' and implicit 'ab' multiply `current_product` # when the next variable or '(' arrives. all_terms = sum_terms + current_product return "+".join(all_terms)✅ Submit now — all tests should pass.
Intuition & how it works
Think of expanding an expression like building combo meals from a restaurant menu. A + gives alternatives within the same course (soup or salad), while multiplication (* or side-by-side concatenation) pairs every combo built so far with every choice in the next course — this is the distributive property, the algebraic rule x * (y + z) = xy + xz. Whenever we hit (, we set our unfinished outer trays aside on a stack (a last-in, first-out list of saved work frames), figure out the full list of choices inside that sub-menu first, and then pair them back with our paused outer trays as soon as ) closes.
A naive attempt that searches the string for * and splices substrings in place quickly tangles up on operator precedence (* binds tighter than +, so p+q*(s+t) must not distribute p into (s+t)) and deeply nested groups like w*(x+(y+z)*u). Instead, maintaining just two lists at the active parenthesis level — sum_terms for completed + branches and current_product (initialized to [""], where the empty string "" is the multiplicative identity for string concatenation, acting just like 1 in arithmetic) — handles both precedence and arbitrary nesting cleanly in one left-to-right scan.
Walk through w*(x+(y+z)*u) (Example 4) step by step:
'w'updatescurrent_productto["w"],'*'needs no action, and'('pushes([], ["w"])ontostackwhile resetting the inner level.'x'and'+'storesum_terms = ["x"]inside the outer parentheses, and the second'('pushes(["x"], [""])ontostack.'y+z'plus')'resolves the inner group to["y", "z"], and'*u'distributes'u'to form["yu", "zu"].- The final
')'combines["x"] + ["yu", "zu"]into["x", "yu", "zu"], pops["w"]fromstack, and distributes to yield"wx+wyu+wzu".
Complexity
Let n be the length of the input expression and L be the character length of the expanded output string.
- Output lower bound (
O(n + L)): Any algorithm must read allninput characters and emit allLoutput characters. Notice thatLitself can grow exponentially withn: chainingkcopies of(x+y)produces2^kterms of lengthk. Linear parser complexity beyond the output means performingO(n)state transitions without exponential scratch structures on top of the output terms being built. - Time:
O(n * L)in the worst case (andO(n + L)on balanced branching like(x+y)*(u+v)*...). We scan thencharacters once;'(','*', and'+'doO(1)amortized list work, while each variable or')'copies strings whose total length never exceedsL(for instance,kconsecutive lettersp*q*r*...copy1 + 2 + ... + k = O(k^2)characters; grouping adjacent letters or building a syntax tree first avoids quadratic copying on long flat chains). - Space:
O(n + L)total (O(n)stack frames beyond active output substrings). Thestackholds at most one frame per'('(<= n / 2frames), and all strings held acrossstack,sum_terms, andcurrent_productrepresent prefixes or pieces of final output terms totaling at mostO(L)characters.
Edge cases
- Single variable or parentheses-free expressions:
"x"->"x","x+y+z"->"x+y+z", and"x*y*z"->"xyz". - Implicit multiplication by concatenation:
"pq","p(q+r)s", and"(p+q)(r+s)"work identically to explicit'*'because'*'is a no-op between factors. - Non-commutativity and duplicate terms:
"(q+p)*(p+q)"yields"qp+qq+pp+pq"(preserving variable order) and"(x+x)*y"yields"xy+xy"(never deduplicating or combining coefficients). - Redundant and deeply nested parentheses:
"((p))*((q+r))"and50-deep((((...x+y...))))*zwork without hitting Python's1000-frame call-stack recursion limit becausestacklives on the heap. - Top-level
'+'mixed with products:"p+q*r*(s+t)+y"distributesq*ronly across(s+t), leavingpandyuntouched.
Common mistakes
- Initializing
current_product = []instead of[""]: an empty list has0elements, so the nested loops indistribute([], ["p"])run0times and erase every product! - Swapping the loop order in
distribute: puttingright_termsas the outer loop turns(x+y)*(u+v)intoxu+yu+xv+yvinstead of the required left-to-rightxu+xv+yu+yv. - Sorting letters inside a term or merging equal terms: variables must preserve their left-to-right appearance (
qp, notpq), and repeated terms remain separate (xy+xy). - Keeping one global
sum_termslist across parentheses:'+'inside(v+w+x)must only separate alternatives inside that group, not flush into the outer expression beforeu*distributes! - Forgetting the final
current_productat')'or end-of-string: the last product inp+q*rhas no trailing'+', so we must always combinesum_terms + current_product.
Alternative approaches
- Recursive-descent parser: A recursive-descent parser is a top-down parser with one mutually recursive function per grammar rule (
parse_sumsplits on'+'and callsparse_product, which splits on factors and callsparse_suminside'(' ... ')'). It performs the exact same list distributions using Python's call stack instead ofstack, though deeply nested parentheses (> 1000levels) can raiseRecursionError. - Stage 1
O(1)extra-space odometer (mixed-radix counter): When'+'appears only inside non-nested parentheses, we never needstackor intermediate lists at all. We represent term numbertas a mixed-radix number — a positional number where each digit position has its own base equal to that parenthesized group's number of'+'-separated choices — soO(1)integer counters pick one choice from each group directly into an output buffer:
def count_choices(expression: str, open_idx: int) -> int:
"""Count '+'-separated alternatives inside a flat '(...)' group."""
choices = 1
idx = open_idx + 1
while expression[idx] != ")":
if expression[idx] == "+":
choices += 1
idx += 1
return choices
def expand_flat_product(expression: str) -> str:
"""Stage 1: expand using O(1) extra space beyond the output (no stack)."""
total_terms = 1
for idx, ch in enumerate(expression):
if ch == "(":
total_terms *= count_choices(expression, idx)
output_chars = []
for term_idx in range(total_terms):
if term_idx > 0:
output_chars.append("+")
suffix_combinations = total_terms
idx = 0
while idx < len(expression):
ch = expression[idx]
if ch == "(":
choices = count_choices(expression, idx)
suffix_combinations //= choices
chosen_branch = (term_idx // suffix_combinations) % choices
branch = 0
idx += 1
while expression[idx] != ")":
if expression[idx] == "+":
branch += 1
elif branch == chosen_branch and expression[idx].isalpha():
output_chars.append(expression[idx])
idx += 1
elif ch.isalpha():
output_chars.append(ch)
idx += 1
return "".join(output_chars)
Follow-up questions
- What if the expanded output contains millions of product terms and cannot fit in RAM at once? Parse the formula once into a compact syntax tree of
SumNodeandProductNodeobjects (O(n)memory), then write a Python generator (yield) that streams expanded terms one at a time without materializing the full list in RAM. At aSumNode, yield every term from each child in turn; at aProductNode, iterate lazily over nested child generators so peak auxiliary memory staysO(n)regardless of how many terms are emitted. - How would the algorithm change if multiplication commuted and identical terms had to be combined with coefficients? Canonicalize each expanded product term by sorting its variable characters alphabetically (
"qp"->"pq"), then accumulate integer counts in a dictionarycounts[canonical_term] += 1. Because Python dictionaries preserve insertion order, iterating overcounts.items()emits combined terms in order of first appearance (or sorted order if canonical output is desired), prefixing any count> 1onto its variable string. - How would you extend your parser to handle subtraction and integer coefficients such as 3(x-2y)? Represent each term as
(coefficient, variables_str)instead of a plain string, using[(1, "")]as the multiplicative identity. Multiplying two terms multiplies their integer coefficients and concatenates their variable strings, while binary-flushescurrent_productintosum_termsand starts the next product segment as[(-1, "")](and unary-at index0or immediately after'('setscurrent_product = [(-1, "")]).
Follow-up questions
- What if the expanded output contains millions of product terms and cannot fit in RAM at once?
- How would the algorithm change if multiplication commuted and identical terms had to be combined with coefficients?
- How would you extend your parser to handle subtraction and integer coefficients such as 3*(x-2*y)?
Similar questions
- Distribute Products Across Parenthesized Sums
- Matrix Product, Fast Power, and Matrix Fibonacci
- LRU Cache, Uniform rand10, and Square Counting
- Balanced Bracket Validation
- Centered Rolling Means and Grouped Interval Merging
- Connecting Doctoral Research to Production Software Engineering
More WeRide interview questions
- Centered Rolling Means and Grouped Interval Merging Medium
- Connecting Doctoral Research to Production Software Engineering Medium
- Comparing Empirical Distributions Across Two Datasets Medium Pro
- Distribute Products Across Parenthesized Sums Medium Pro
- LRU Cache, Uniform rand10, and Square Counting Medium Pro
- Matrix Product, Fast Power, and Matrix Fibonacci Medium Pro
- Balanced Bracket Validation Medium Pro