This notebook was prepared by [Rishi Rajasekaran](https://github.com/rishihot55). Source and license info is available on [Github](https://github.com/donnemartin/interactive-coding-challenges).

Challenge Notebook

Problem: Print all valid combinations of n-pairs of parentheses.

Constraints

  • None

Test Cases

  • 0 -> []
  • 1 -> [()]
  • 2 -> [(()), ()()]
  • 3 -> [((())), (()()), (())(), ()(()), ()()()]

Algorithm

Refer to the Solution Notebook. If you are stuck and need a hint, the solution notebook's algorithm discussion might be a good place to start.

Code


In [ ]:
def parentheses_util(no_left, no_right, pair_string, result):
    # TODO: implement parentheses pairing here
    pass


def pair_parentheses(n):
    result_set = set()
    if n == 0:
        return result_set
    parentheses_util(n, n, '', result_set)
    return result_set

Unit Test


In [ ]:
# %load 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()

Solution Notebook

Review the Solution Notebook for a discussion on algorithms and code solutions.


In [ ]: