{
 "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: Sort a stack.  You can use another stack as a buffer.\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",
    "* When sorted, should the largest element be at the top or bottom?\n",
    "    * Top\n",
    "* Can you have duplicate values like 5, 5?\n",
    "    * Yes\n",
    "* Can we assume we already have a stack class that can be used for this problem?\n",
    "    * Yes\n",
    "* Can we assume this fits memory?\n",
    "    * Yes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test Cases\n",
    "\n",
    "* Empty stack -> None\n",
    "* One element stack\n",
    "* Two or more element stack (general case)\n",
    "* Already sorted stack"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Algorithm\n",
    "\n",
    "* Our buffer will hold elements in reverse sorted order, smallest at the top\n",
    "* Store the current top element in a temp variable\n",
    "* While stack is not empty\n",
    "    * While buffer is not empty or buffer top is > than temp\n",
    "        * Move buffer top to stack\n",
    "    * Move temp to top of buffer\n",
    "* Return buffer\n",
    "\n",
    "Complexity:\n",
    "* Time: O(n^2)\n",
    "* Space: O(n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "%run ../stack/stack.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class MyStack(Stack):\n",
    "\n",
    "    def sort(self):\n",
    "        buff = MyStack()\n",
    "        while not self.is_empty():\n",
    "            temp = self.pop()\n",
    "            if buff.is_empty() or temp >= buff.peek():\n",
    "                buff.push(temp)\n",
    "            else:\n",
    "                while not buff.is_empty() and temp < buff.peek():\n",
    "                    self.push(buff.pop())\n",
    "                buff.push(temp)\n",
    "        return buff"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The solution can be further simplified:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class MyStackSimplified(Stack):\n",
    "\n",
    "    def sort(self):\n",
    "        buff = MyStack()\n",
    "        while not self.is_empty():\n",
    "            temp = self.pop()\n",
    "            while not buff.is_empty() and temp < buff.peek():\n",
    "                self.push(buff.pop())\n",
    "            buff.push(temp)\n",
    "        return buff"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unit Test\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting test_sort_stack.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile test_sort_stack.py\n",
    "from random import randint\n",
    "from nose.tools import assert_equal\n",
    "\n",
    "\n",
    "class TestSortStack(object):\n",
    "\n",
    "    def get_sorted_stack(self, stack, numbers):\n",
    "        for x in numbers:\n",
    "            stack.push(x)\n",
    "        sorted_stack = stack.sort()\n",
    "        return sorted_stack\n",
    "\n",
    "    def test_sort_stack(self, stack):\n",
    "        print('Test: Empty stack')\n",
    "        sorted_stack = self.get_sorted_stack(stack, [])\n",
    "        assert_equal(sorted_stack.pop(), None)\n",
    "\n",
    "        print('Test: One element stack')\n",
    "        sorted_stack = self.get_sorted_stack(stack, [1])\n",
    "        assert_equal(sorted_stack.pop(), 1)\n",
    "\n",
    "        print('Test: Two or more element stack (general case)')\n",
    "        num_items = 10\n",
    "        numbers = [randint(0, 10) for x in range(num_items)]\n",
    "        sorted_stack = self.get_sorted_stack(stack, numbers)\n",
    "        sorted_numbers = []\n",
    "        for _ in range(num_items):\n",
    "            sorted_numbers.append(sorted_stack.pop())\n",
    "        assert_equal(sorted_numbers, sorted(numbers, reverse=True))\n",
    "\n",
    "        print('Success: test_sort_stack')\n",
    "\n",
    "\n",
    "def main():\n",
    "    test = TestSortStack()\n",
    "    test.test_sort_stack(MyStack())\n",
    "    test.test_sort_stack(MyStackSimplified())\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Test: Empty stack\n",
      "Test: One element stack\n",
      "Test: Two or more element stack (general case)\n",
      "Success: test_sort_stack\n",
      "Test: Empty stack\n",
      "Test: One element stack\n",
      "Test: Two or more element stack (general case)\n",
      "Success: test_sort_stack\n"
     ]
    }
   ],
   "source": [
    "%run -i test_sort_stack.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
}
