# Check for balanced parentheses in an expression O(1) space O(N^2) time complexity in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string str containing these brackets '(', ')', '{', '}', '[' and ']', we have to check whether brackets are balanced or not. We can say brackets are balanced when Opening and closing bracket types are of same type. Brackets are closed in correct order.

So, if the input is like {([])}, then the output will be True.

To solve this, we will follow these steps −

• cnt := 0
• i := 0
• j := -1
• Define a function solve() . This will take s, temp
• cnt := cnt - 1
• s := a new list from s
• if j > -1 and s[j] is same as temp, then
• s[i] := '#'
• s[j] := '#'
• while j >= 0 and s[j] is same as '#', do
• j := j - 1
• i := i + 1>
• return 1
• otherwise,
• return 0
• From the main method, do the following −
• if size of s is same as 0, then
• return True
• otherwise,
• ans := False
• while i < size of s is non-zero, do
• if s[i] is same as '}', then
• ans := solve(s, '{')
• if ans is same as 0, then
• return False
• otherwise when s[i] is same as ')', then
• ans := solve(s, '(')
• if ans is same as 0, then
• return False
• otherwise when s[i] is same as ']', then
• ans := solve(s, '[')
• if ans is same as 0, then
• return False
• otherwise,
• j := i
• i := i + 1
• cnt := cnt + 1
• if cnt is not same as 0, then
• return False
• return True

## Example

Let us see the following implementation to get better understanding −

Live Demo

cnt = 0
i = 0
j = -1
def solve(s, temp):
global i, j, cnt
cnt -= 1
s = list(s)
if j > -1 and s[j] == temp:
s[i] = '#'
s[j] = '#'
while j >= 0 and s[j] == '#':
j -= 1
i += 1
return 1
else:
return 0
def bracketOrderCheck(s):
global i, j, cnt
if len(s) == 0:
return True
else:
ans = False
while i < len(s):
if s[i] == '}':
ans = solve(s, '{')
if ans == 0:
return False
elif s[i] == ')':
ans = solve(s, '(')
if ans == 0:
return False
elif s[i] == ']':
ans = solve(s, '[')
if ans == 0:
return False
else:
j = i
i += 1
cnt += 1
if cnt != 0:
return False
return True
print(bracketOrderCheck("{([])}"))

## Input

"{(()[])}"

## Output

True