Expand algebraic expression with distribution
Company: WeRide
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates parsing of algebraic expressions, application of the distributive law, string manipulation, and algorithmic reasoning about time and extra-space complexity.
Constraints
- 1 <= len(expr)
- expr contains only lowercase letters 'a'-'z', '+', '*', '(' and ')'
- Parentheses are balanced and there are no empty groups
- Multiplication has higher precedence than addition; operators are binary
- Within a monomial, letters appear in multiplication (left-to-right) order and are NOT re-sorted
Examples
Input: ("(a+b)*(c+d)",)
Expected Output: "ac+ad+bc+bd"
Explanation: Distribute the product of two binomials: each term of the first sum times each term of the second.
Input: ("a+b*c*(d+e+f)+k+m*(g+h)+i",)
Expected Output: "a+bcd+bce+bcf+k+mg+mh+i"
Explanation: Follow-up case with '+' outside parentheses: 'a', 'k', 'i' pass through; b*c*(d+e+f) expands to bcd+bce+bcf; m*(g+h) expands to mg+mh.
Input: ("a",)
Expected Output: "a"
Explanation: Edge case: a single letter is already fully expanded.
Input: ("a*b",)
Expected Output: "ab"
Explanation: A single product of two letters becomes the concatenated monomial 'ab'.
Input: ("(a+b)*(c+d)*(e+f)",)
Expected Output: "ace+acf+ade+adf+bce+bcf+bde+bdf"
Explanation: Three binomials multiplied: 2*2*2 = 8 monomials, each a choice of one letter from each factor in order.
Input: ("(a+b+c)*d",)
Expected Output: "ad+bd+cd"
Explanation: Distribute a trinomial across a single letter on the right.
Input: ("x*(y+z)",)
Expected Output: "xy+xz"
Explanation: Single letter times a binomial distributes to two monomials.
Hints
- Model the expression with a recursive-descent grammar: expr = term ('+' term)*, term = factor ('*' factor)*, factor = letter | '(' expr ')'.
- Have each parse function return a LIST of monomials (strings). A sum concatenates the two lists; a product takes the cartesian product, concatenating each left monomial with each right monomial in order.
- A single letter parses to a one-element list [letter]. Joining the final list with '+' gives the answer. The recursion stack provides the O(n) extra space the follow-up permits.