• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
June 13, 2022 |4.5K Views

Check for balanced parentheses in an expression

  Share   Like
Description
Discussion

Given a string of length n having parentheses in it, your task is to find whether given string has balanced parentheses or not. Please note there is constraint on space i.e. we are allowed to use only O(1) extra space.

If k = 1, then we will simply keep a count variable c = 0, whenever we encounter an opening parentheses we will increment c and whenever we encounter a closing parentheses we will reduce the count of c, At any stage we shouldn’t have c < 0 and at the end we must have c = 0 for string to be balanced. 
Following is the idea of our algorithm for this problem. For any opening bracket say ‘[‘ we find its matching closing bracket ‘]’. Let’s say index of ‘[‘ was i and index of ‘]’ was j then following conditions must be true:

Check for balanced parentheses in an expression  : https://www.geeksforgeeks.org/check-balanced-parentheses-expression-o1-space/