This notebook was prepared by [Rishi Rajasekaran](https://github.com/rishihot55). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
Let l and r denote the number of left and right parentheses remaining at any given point.
The algorithm makes use of the following conditions applied recursively:
l > 0.r > l. Violation of the aforementioned condition produces an unbalanced string of parentheses.l = 0 and r = 0, then the resultant string produced is balanced.The algorithm can be rephrased as:
l = 0 and r = 0l > 0r > lComplexity:
O(4^n/n^(3/2)). See Catalan numbersO(n) (Due to the implicit call stack storing a maximum of 2n function calls)
In [1]:
def parentheses_util(no_left, no_right, pair_string, result):
if no_left == 0 and no_right == 0:
result.add(pair_string)
else:
if no_left > 0:
parentheses_util(no_left - 1, no_right, pair_string + '(', result)
if no_right > no_left:
parentheses_util(no_left, no_right - 1, pair_string + ')', result)
def pair_parentheses(n):
result_set = set()
if n == 0:
return result_set
parentheses_util(n, n, '', result_set)
return result_set
In [2]:
%%writefile test_n_pairs_parentheses.py
from nose.tools import assert_equal
class TestPairParentheses(object):
def test_pair_parentheses(self, solution):
assert_equal(solution(0), set([]))
assert_equal(solution(1), set(['()']))
assert_equal(solution(2), set(['(())',
'()()']))
assert_equal(solution(3), set(['((()))',
'(()())',
'(())()',
'()(())',
'()()()']))
print('Success: test_pair_parentheses')
def main():
test = TestPairParentheses()
test.test_pair_parentheses(pair_parentheses)
if __name__ == '__main__':
main()
In [3]:
%run -i test_n_pairs_parentheses.py