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*p becomes qp, never pq).
  • Left-to-right distribution order: When multiplying (L_1 + L_2 + ...) * (R_1 + R_2 + ...), pair L_1 with every R_j in order before advancing to L_2, and so forth.
  • No term combining: Keep identical product terms separate rather than introducing numerical coefficients or removing duplicates (for example, (x+x)*y becomes xy+xy).

In an interview setting, this problem builds in two stages:

  1. Restricted chains: When '+' occurs solely inside flat, unnested parenthesized groups, every expanded product can be emitted using O(1) auxiliary working variables beyond the output buffer (no stack required).
  2. Arbitrary nesting (judge target): Implement expand_expression(expression: str) -> str for any valid input where '+' may appear at any level and parentheses may nest to arbitrary depth, using O(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) <= 200
  • expression contains 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^5 characters.

Step-by-step walkthrough

  1. 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 rule x * (y + z) = xy + xz — until all parentheses and multiplications disappear.

    Four formatting rules completely pin down the answer:

    1. Concatenation means multiplication: Both p*q and pq (or p(q+r) and (p+q)(r+s)) represent multiplication, and output products are written without * (pq).
    2. Keep variable order inside every term: Multiplication is not sorted alphabetically — q*p must stay qp, never pq.
    3. Left-to-right expansion order: In (x+y+z)*(u+v), we hold x fixed while stepping through u, v, then hold y fixed while stepping through u, v, and finally hold z fixed, giving xu+xv+yu+yv+zu+zv.
    4. Never merge duplicate terms: (x+x)*y expands to xy+xy, not 2xy or xy.
  2. 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) has 2 choices, (q+r) has 2 choices).

    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         knpr
    

    Because term index t encodes which option to pick from each (...) group via integer division and remainder, Stage 1 can emit all terms using O(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.

  3. 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, keeping left_terms as 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 as 1 is the multiplicative identity in arithmetic (1 * x = x) while 0 wipes everything out (0 * x = 0), distribute([""], ["p"]) gives ["" + "p"] = ["p"], whereas distribute([], ["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
    
  4. Handle one flat level of `+` and `*` without parentheses

    Before adding parentheses, trace how operator precedence (* binds tighter than +) works on a flat string like p+q*r as 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! Both q*r and implicit qr simply multiply current_product when r arrives.
    • '+': closes the active multiplication chain: append current_product into sum_terms, then reset current_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"
    
  5. Add a stack to handle nested parentheses

    Now suppose we hit '(' in the middle of a product, such as q*r*(s+t). We cannot multiply current_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) onto stack to pause the outer level, then reset sum_terms = [] and current_product = [""] for the new inner group.
    • On ')': the inner group is now finished as group_terms = sum_terms + current_product. Pop the paused outer (sum_terms, current_product) from stack, 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)
    
  6. 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"
    
  7. 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:

  1. 'w' updates current_product to ["w"], '*' needs no action, and '(' pushes ([], ["w"]) onto stack while resetting the inner level.
  2. 'x' and '+' store sum_terms = ["x"] inside the outer parentheses, and the second '(' pushes (["x"], [""]) onto stack.
  3. 'y+z' plus ')' resolves the inner group to ["y", "z"], and '*u' distributes 'u' to form ["yu", "zu"].
  4. The final ')' combines ["x"] + ["yu", "zu"] into ["x", "yu", "zu"], pops ["w"] from stack, 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 all n input characters and emit all L output characters. Notice that L itself can grow exponentially with n: chaining k copies of (x+y) produces 2^k terms of length k. Linear parser complexity beyond the output means performing O(n) state transitions without exponential scratch structures on top of the output terms being built.
  • Time: O(n * L) in the worst case (and O(n + L) on balanced branching like (x+y)*(u+v)*...). We scan the n characters once; '(', '*', and '+' do O(1) amortized list work, while each variable or ')' copies strings whose total length never exceeds L (for instance, k consecutive letters p*q*r*... copy 1 + 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). The stack holds at most one frame per '(' (<= n / 2 frames), and all strings held across stack, sum_terms, and current_product represent prefixes or pieces of final output terms totaling at most O(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))" and 50-deep ((((...x+y...))))*z work without hitting Python's 1000-frame call-stack recursion limit because stack lives on the heap.
  • Top-level '+' mixed with products: "p+q*r*(s+t)+y" distributes q*r only across (s+t), leaving p and y untouched.

Common mistakes

  • Initializing current_product = [] instead of [""]: an empty list has 0 elements, so the nested loops in distribute([], ["p"]) run 0 times and erase every product!
  • Swapping the loop order in distribute: putting right_terms as the outer loop turns (x+y)*(u+v) into xu+yu+xv+yv instead of the required left-to-right xu+xv+yu+yv.
  • Sorting letters inside a term or merging equal terms: variables must preserve their left-to-right appearance (qp, not pq), and repeated terms remain separate (xy+xy).
  • Keeping one global sum_terms list across parentheses: '+' inside (v+w+x) must only separate alternatives inside that group, not flush into the outer expression before u* distributes!
  • Forgetting the final current_product at ')' or end-of-string: the last product in p+q*r has no trailing '+', so we must always combine sum_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_sum splits on '+' and calls parse_product, which splits on factors and calls parse_sum inside '(' ... ')'). It performs the exact same list distributions using Python's call stack instead of stack, though deeply nested parentheses (> 1000 levels) can raise RecursionError.
  • Stage 1 O(1) extra-space odometer (mixed-radix counter): When '+' appears only inside non-nested parentheses, we never need stack or intermediate lists at all. We represent term number t as 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 — so O(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 SumNode and ProductNode objects (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 a SumNode, yield every term from each child in turn; at a ProductNode, iterate lazily over nested child generators so peak auxiliary memory stays O(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 dictionary counts[canonical_term] += 1. Because Python dictionaries preserve insertion order, iterating over counts.items() emits combined terms in order of first appearance (or sorted order if canonical output is desired), prefixing any count > 1 onto 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 - flushes current_product into sum_terms and starts the next product segment as [(-1, "")] (and unary - at index 0 or immediately after '(' sets current_product = [(-1, "")]).

Follow-up questions

Similar questions

More WeRide interview questions

All 8 WeRide questions →