Expand algebraic expression with distribution
WeRideSoftware Engineer · Technical ScreenLast updated
This question evaluates parsing of algebraic expressions, application of the distributive law, string manipulation, and algorithmic reasoning about time and extra-space complexity.
Question
Given an expression of lowercase letters, '+', '', and parentheses with no '+' outside any parentheses, return an equivalent expression containing only '+' by fully expanding all products (e.g., (a+b)(c+d) → ac+ad+bc+bd). Achieve O(
- extra-space complexity. Follow-up: If '+' may appear outside parentheses (e.g., a+bc(d+e+f)+k+m*(g+h)+i), output the fully expanded '+'-only form (a+bcd+bce+bcf+k+mg+mh+i). Provide working code that may use O(n) extra space (e.g., a stack).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.