{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Solution Notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Problem: Find all valid combinations of n-pairs of parentheses.\n",
    "\n",
    "* [Constraints](#Constraints)\n",
    "* [Test Cases](#Test-Cases)\n",
    "* [Algorithm](#Algorithm)\n",
    "* [Code](#Code)\n",
    "* [Unit Test](#Unit-Test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Constraints\n",
    "\n",
    "* Is the input an integer representing the number of pairs?\n",
    "    * Yes\n",
    "* Can we assume the inputs are valid?\n",
    "    * No\n",
    "* Is the output a list of valid combinations?\n",
    "    * Yes\n",
    "* Should the output have duplicates?\n",
    "    * No\n",
    "* Can we assume this fits memory?\n",
    "    * Yes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test Cases\n",
    "\n",
    "<pre>\n",
    "* None -> Exception\n",
    "* Negative -> Exception\n",
    "* 0 -> []\n",
    "* 1 -> ['()']\n",
    "* 2 -> ['(())', '()()']\n",
    "* 3 -> ['((()))', '(()())', '(())()', '()(())', '()()()']\n",
    "</pre>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Algorithm\n",
    "\n",
    "Let `l` and `r` denote the number of left and right parentheses remaining at any given point. \n",
    "The algorithm makes use of the following conditions applied recursively:\n",
    "* Left braces can be inserted any time, as long as we do not exhaust them i.e. `l > 0`.\n",
    "* Right braces can be inserted, as long as the number of right braces remaining is greater than the left braces remaining i.e. `r > l`. Violation of the aforementioned condition produces an unbalanced string of parentheses.\n",
    "* If both left and right braces have been exhausted i.e. `l = 0 and r = 0`, then the resultant string produced is balanced.\n",
    "\n",
    "The algorithm can be rephrased as:\n",
    "* Base case: `l = 0 and r = 0`\n",
    "    - Add the string generated to the result set\n",
    "* Case 1: `l > 0`\n",
    "    - Add a left parenthesis to the parentheses string.\n",
    "    - Recurse (l - 1, r, new_string, result_set)\n",
    "* Case 2: `r > l`\n",
    "    - Add a right parenthesis to the parentheses string.\n",
    "    - Recurse (l, r - 1, new_string, result_set)\n",
    "\n",
    "Complexity:\n",
    "* Time: `O(4^n/n^(3/2))`, see [Catalan numbers](https://en.wikipedia.org/wiki/Catalan_number#Applications_in_combinatorics) - 1, 1, 2, 5, 14, 42, 132...\n",
    "* Space complexity: `O(n)`, due to the implicit call stack storing a maximum of 2n function calls)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Parentheses(object):\n",
    "\n",
    "    def find_pair(self, num_pairs):\n",
    "        if num_pairs is None:\n",
    "            raise TypeError('num_pairs cannot be None')\n",
    "        if num_pairs < 0:\n",
    "            raise ValueError('num_pairs cannot be < 0')\n",
    "        if not num_pairs:\n",
    "            return []\n",
    "        results = []\n",
    "        curr_results = []\n",
    "        self._find_pair(num_pairs, num_pairs, curr_results, results)\n",
    "        return results\n",
    "\n",
    "    def _find_pair(self, nleft, nright, curr_results, results):\n",
    "        if nleft == 0 and nright == 0:\n",
    "            results.append(''.join(curr_results))\n",
    "        else:\n",
    "            if nleft >= 0:\n",
    "                self._find_pair(nleft-1, nright, curr_results+['('], results)\n",
    "            if nright > nleft:\n",
    "                self._find_pair(nleft, nright-1, curr_results+[')'], results)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unit Test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting test_n_pairs_parentheses.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile test_n_pairs_parentheses.py\n",
    "from nose.tools import assert_equal, assert_raises\n",
    "\n",
    "\n",
    "class TestPairParentheses(object):\n",
    "\n",
    "    def test_pair_parentheses(self):\n",
    "        parentheses = Parentheses()\n",
    "        assert_raises(TypeError, parentheses.find_pair, None)\n",
    "        assert_raises(ValueError, parentheses.find_pair, -1)\n",
    "        assert_equal(parentheses.find_pair(0), [])\n",
    "        assert_equal(parentheses.find_pair(1), ['()'])\n",
    "        assert_equal(parentheses.find_pair(2), ['(())',\n",
    "                                                '()()'])\n",
    "        assert_equal(parentheses.find_pair(3), ['((()))',\n",
    "                                                '(()())',\n",
    "                                                '(())()',\n",
    "                                                '()(())',\n",
    "                                                '()()()'])\n",
    "        print('Success: test_pair_parentheses')\n",
    "\n",
    "\n",
    "def main():\n",
    "    test = TestPairParentheses()\n",
    "    test.test_pair_parentheses()\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Success: test_pair_parentheses\n"
     ]
    }
   ],
   "source": [
    "%run -i test_n_pairs_parentheses.py"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
