VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-two-expressions-brackets/

⇱ Check if two expressions with brackets have same result - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if two expressions with brackets have same result

Last Updated : 18 Mar, 2025

Given two expressions in the form of strings. The task is to compare them and check if they are similar. Expressions consist of lowercase alphabets, '+', '-' and '( )'.

Examples: 

Input : exp1 = "-(a+b+c)"
exp2 = "-a-b-c"
Output : Yes
Explanation : The first expression, when simplified by distributing the negative sign, matches the second expression, hence they are similar.

Input : exp1 = "-(c+b+a)"
exp2 = "-c-b-a"
Output : Yes
Explanation : The order of terms inside parentheses does not affect the result, and distributing the negative sign yields a match, so the expressions are similar.

Input : exp1 = "a-b-(c-d)"
exp2 = "a-b-c-d"
Output : No
Explanation : The negative sign distribution inside the parentheses leads to different signs for the terms, making the expressions not similar.

Approach - Sign Propagation - O(n) time and O(n) space

This approach tracks the global and local signs in an expression. The global sign affects operands within parentheses, while the local sign applies to each operand individually. The final sign of an operand is the product of its local and global signs.

For example, in a + b - (c - d), the expression evaluates to a + b - c + d, where the global sign inside parentheses flips the signs of c and d.

A stack keeps track of global signs, and a count vector records operand counts. Both expressions are evaluated in opposite ways, and if the count vector ends with all zeros, the expressions are considered equivalent.


Output
Yes


Comment
Article Tags: