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
Check if concatenation of two strings is balanced or not in Python
Suppose we have two bracket sequences s and t containing only parentheses '(' and ')'. We need to check whether concatenating these strings in either order (s + t or t + s) results in a balanced parentheses string.
So, if the input is like s = "()()))", t = "()(()(", then the output will be True because if we concatenate t + s, we get "()(()(()()))", which is balanced.
Algorithm
To solve this problem, we follow these steps ?
- Create a function
is_balanced_parenthesis()to check if a string has balanced parentheses - Use a stack to track opening brackets
- For each character in the string:
- If it's
'(', push it onto the stack - If it's
')', try to match it with an opening bracket from the stack
- If it's
- Check both concatenation orders:
s + tandt + s - Return
Trueif either order produces a balanced string
Implementation
def is_balanced_parenthesis(string):
stack = []
for i in range(len(string)):
if string[i] == '(':
stack.append(string[i])
else:
if len(stack) == 0:
return False
else:
stack.pop()
if len(stack) > 0:
return False
return True
def solve(s, t):
if is_balanced_parenthesis(s + t):
return True
return is_balanced_parenthesis(t + s)
s = "()()))"
t = "()(()()"
print(solve(s, t))
True
How It Works
The is_balanced_parenthesis() function uses a stack-based approach ?
- For each opening bracket
'(', we push it onto the stack - For each closing bracket
')', we try to pop from the stack - If the stack is empty when we encounter a
')', the string is unbalanced - After processing all characters, the stack should be empty for a balanced string
Testing Different Cases
def is_balanced_parenthesis(string):
stack = []
for char in string:
if char == '(':
stack.append(char)
else:
if not stack:
return False
stack.pop()
return len(stack) == 0
def solve(s, t):
return is_balanced_parenthesis(s + t) or is_balanced_parenthesis(t + s)
# Test cases
test_cases = [
("()()))", "()(()("), # True
("((", "))"), # True
("(()", ")"), # True
("((", "("), # False
]
for i, (s, t) in enumerate(test_cases, 1):
result = solve(s, t)
print(f"Test {i}: s='{s}', t='{t}' ? {result}")
Test 1: s='()()))', t='()(()(', ? True
Test 2: s='((', t='))', ? True
Test 3: s='(()', t=')', ? True
Test 4: s='((', t='(', ? False
Optimized Version
We can simplify the code by using Python's built-in features ?
def is_balanced(s):
count = 0
for char in s:
if char == '(':
count += 1
elif char == ')':
count -= 1
if count < 0:
return False
return count == 0
def check_concatenation(s, t):
return is_balanced(s + t) or is_balanced(t + s)
# Example usage
s = "()()))"
t = "()(()()"
print(f"Can concatenate '{s}' and '{t}' to form balanced string: {check_concatenation(s, t)}")
Can concatenate '()()))' and '()(()()', to form balanced string: True
Conclusion
This solution efficiently checks if two parentheses strings can be concatenated in either order to form a balanced string. The stack-based approach ensures O(n) time complexity, where n is the total length of both strings.
