{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook was prepared by [Donne Martin](http://donnemartin.com). 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: Add two numbers whose digits are stored in a linked list in reverse order.\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",
    "* Can we assume this is a non-circular, singly linked list?\n",
    "    * Yes\n",
    "* Do we expect the return to be in reverse order too?\n",
    "    * Yes\n",
    "* What if one of the inputs is None?\n",
    "    * Return None for an invalid operation\n",
    "* How large are these numbers--can they fit in memory?\n",
    "    * Yes\n",
    "* Can we assume we already have a linked list class that can be used for this problem?\n",
    "    * Yes\n",
    "* Can we assume this fits in memory?\n",
    "    * Yes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test Cases\n",
    "\n",
    "* Empty list(s) -> None\n",
    "* Add values of different lengths\n",
    "    * Input 1: 6->5->None\n",
    "    * Input 2: 9->8->7\n",
    "    * Result: 5->4->8\n",
    "* Add values of same lengths\n",
    "    * Exercised from values of different lengths\n",
    "    * Done here for completeness"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Algorithm\n",
    "\n",
    "We could solve this with an iterative or a recursive algorithm, both are well suited for this exercise.  We'll use a recursive algorithm for practice with recursion.  Note this takes an extra space of O(m) where m is the recursion depth.\n",
    "\n",
    "* Base case:\n",
    "    * if first and second lists are None AND carry is zero\n",
    "        * Return None\n",
    "* Recursive case:\n",
    "    * Set `value` to `carry`\n",
    "    * Add both nodes' `data` to `value`\n",
    "    * Set the `carry` to 1 if `value >= 10, else 0`\n",
    "    * Set the `remainder` to `value % 10`\n",
    "    * Create a `node` with the `remainder`\n",
    "    * Set `node.next` to a recursive call on the `next` nodes, passing in the `carry`\n",
    "    * Return `node`\n",
    "\n",
    "Complexity:\n",
    "* Time: O(n)\n",
    "* Space: O(m), extra space for result and recursion depth\n",
    "\n",
    "Notes:\n",
    "* Careful with adding if the lists differ\n",
    "    * Only add if a node is not None\n",
    "    * Alternatively, we could add trailing zeroes to the smaller list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "%run ../linked_list/linked_list.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class MyLinkedList(LinkedList):\n",
    "\n",
    "    def _add_reverse(self, first_node, second_node, carry):\n",
    "        # Base case\n",
    "        if first_node is None and second_node is None and not carry:\n",
    "            return None\n",
    "\n",
    "        # Recursive case\n",
    "        value = carry\n",
    "        value += first_node.data if first_node is not None else 0\n",
    "        value += second_node.data if second_node is not None else 0\n",
    "        carry = 1 if value >= 10 else 0\n",
    "        value %= 10\n",
    "        node = Node(value)\n",
    "        node.next = self._add_reverse(\n",
    "            first_node.next if first_node is not None else None,\n",
    "            second_node.next if first_node is not None else None,\n",
    "            carry)\n",
    "        return node\n",
    "\n",
    "    def add_reverse(self, first_list, second_list):\n",
    "        # See constraints\n",
    "        if first_list is None or second_list is None:\n",
    "            return None\n",
    "        head = self._add_reverse(first_list.head, second_list.head, 0)\n",
    "        return MyLinkedList(head)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unit Test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting test_add_reverse.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile test_add_reverse.py\n",
    "from nose.tools import assert_equal\n",
    "\n",
    "\n",
    "class TestAddReverse(object):\n",
    "\n",
    "    def test_add_reverse(self):\n",
    "        print('Test: Empty list(s)')\n",
    "        assert_equal(MyLinkedList().add_reverse(None, None), None)\n",
    "        assert_equal(MyLinkedList().add_reverse(Node(5), None), None)\n",
    "        assert_equal(MyLinkedList().add_reverse(None, Node(10)), None)\n",
    "\n",
    "        print('Test: Add values of different lengths')\n",
    "        # Input 1: 6->5->None\n",
    "        # Input 2: 9->8->7\n",
    "        # Result: 5->4->8\n",
    "        first_list = MyLinkedList(Node(6))\n",
    "        first_list.append(5)\n",
    "        second_list = MyLinkedList(Node(9))\n",
    "        second_list.append(8)\n",
    "        second_list.append(7)\n",
    "        result = MyLinkedList().add_reverse(first_list, second_list)\n",
    "        assert_equal(result.get_all_data(), [5, 4, 8])\n",
    "\n",
    "        print('Test: Add values of same lengths')\n",
    "        # Input 1: 6->5->4\n",
    "        # Input 2: 9->8->7\n",
    "        # Result: 5->4->2->1\n",
    "        first_head = Node(6)\n",
    "        first_list = MyLinkedList(first_head)\n",
    "        first_list.append(5)\n",
    "        first_list.append(4)\n",
    "        second_head = Node(9)\n",
    "        second_list = MyLinkedList(second_head)\n",
    "        second_list.append(8)\n",
    "        second_list.append(7)\n",
    "        result = MyLinkedList().add_reverse(first_list, second_list)\n",
    "        assert_equal(result.get_all_data(), [5, 4, 2, 1])\n",
    "\n",
    "        print('Success: test_add_reverse')\n",
    "\n",
    "\n",
    "def main():\n",
    "    test = TestAddReverse()\n",
    "    test.test_add_reverse()\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Test: Empty list(s)\n",
      "Test: Add values of different lengths\n",
      "Test: Add values of same lengths\n",
      "Success: test_add_reverse\n"
     ]
    }
   ],
   "source": [
    "%run -i test_add_reverse.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
}
