Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Removing parentheses from mathematical expressions in JavaScript
When working with mathematical expressions in JavaScript, you may need to remove parentheses while preserving the correct operations and operands. This involves carefully tracking signs and handling nested expressions.
Problem
We need to write a JavaScript function that takes a string of mathematical expressions and removes parentheses while keeping operations and operands in their correct positions with proper signs.
For example, if the input is:
const str = 'u-(v-w-(x+y))-z';
The expected output should be:
u-v+w+x+y-z
How It Works
The algorithm uses a stack to track sign changes when encountering parentheses. When we see a minus sign before parentheses, it flips the signs of all operations inside those parentheses.
Example
const str = 'u-(v-w-(x+y))-z';
const removeParentheses = (str = '') => {
let stack = []
let lastSign = '+'
for (let char of str) {
if (char === '(' || char === ')') {
lastSign = stack[stack.length - 1] || '+'
} else if (char === '+') {
if (stack[stack.length - 1] !== '-' && stack[stack.length - 1] !== '+') {
stack.push(lastSign)
}
} else if (char === '-') {
if (lastSign === '-') {
if (stack[stack.length - 1] === '-') stack.pop()
stack.push('+')
} else {
if (stack[stack.length - 1] === '+') stack.pop()
stack.push('-')
}
} else {
stack.push(char)
}
}
return stack.join('').replace(/^\+/, '')
};
console.log(removeParentheses(str));
u-v+w+x+y-z
Step-by-Step Breakdown
// Test with a simpler example first
const simpleExpr = 'a-(b+c)';
console.log('Input:', simpleExpr);
console.log('Output:', removeParentheses(simpleExpr));
// Test with multiple levels
const complexExpr = 'x+(y-(z-w))';
console.log('Input:', complexExpr);
console.log('Output:', removeParentheses(complexExpr));
Input: a-(b+c) Output: a-b-c Input: x+(y-(z-w)) Output: x+y-z+w
Key Points
- Use a stack to track sign changes at each parenthesis level
- When encountering '-' before '(', flip signs inside the parentheses
- Handle nested parentheses by maintaining the current sign context
- Remove leading '+' signs from the final result
Conclusion
This algorithm effectively removes parentheses from mathematical expressions by tracking sign changes with a stack. It handles nested parentheses and maintains proper mathematical operations throughout the transformation.
