Remove parentheses from a plus/minus expression by propagating signs
Company: Oracle
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Given an algebraic expression of single-letter variables joined by plus and minus signs, with nested parentheses and unary minus, rewrite it without parentheses. Each variable keeps its position and takes the sign it effectively carries. The problem tests parsing, sign propagation through nested groups, and handling very deep nesting.
Read the full Oracle Software Engineer interview experience this question came from
Constraints
- 1 <= len(expression) <= 10^5
- expression contains only lowercase letters 'a' to 'z' and the characters '+', '-', '(' and ')', with no spaces.
- expression is valid under the grammar expression := ['-'] term (('+' | '-') term)*, term := letter | '(' expression ')': parentheses are balanced, no group is empty, and every operator has an operand on its right; a unary minus appears only at the very start or right after '(' and there is no unary plus.
- Parentheses may be nested to a depth close to len(expression) / 2.
Examples
Input: ('a',)
Expected Output: 'a'
Explanation: Minimum valid input: a single positive variable is written with no sign.
Input: ('-a',)
Expected Output: '-a'
Explanation: A lone unary minus makes the only variable negative, so the output starts with '-'.
Hints
- For each variable, count the minus signs that apply to it: the one written directly before its own term (binary or unary) plus one for every enclosing group that has a minus directly before it. Only whether that count is odd or even matters.
- A minus in front of a group stops applying at that group's closing parenthesis; the terms after it are back in the enclosing context.
- Nesting can be close to len(expression) / 2 levels deep, and a leading unary minus belongs only to the first term of the expression.