KatInterview

Distribute and Expand Algebraic Products

StringsAuto-graded · 27 test cases
MediumAuto-gradedStringsparsingrecursionstring-manipulation

Last 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 * b becomes ab).
  • The distributive property means x * (y + z) expands to xy + xz, and (a + b) * (c + d) expands to ac + 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., abc is a * 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.