{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "This notebook was prepared by [Donne Martin](https://github.com/donnemartin). 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: Implement a priority queue backed by an array.\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", "* Do we expect the methods to be insert, extract_min, and decrease_key?\n", " * Yes\n", "* Can we assume there aren't any duplicate keys?\n", " * Yes\n", "* Do we need to validate inputs?\n", " * No\n", "* Can we assume this fits memory?\n", " * Yes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Test Cases\n", "\n", "### insert\n", "\n", "* `insert` general case -> inserted node\n", "\n", "### extract_min\n", "\n", "* `extract_min` from an empty list -> None\n", "* `extract_min` general case -> min node\n", "\n", "### decrease_key\n", "\n", "* `decrease_key` an invalid key -> None\n", "* `decrease_key` general case -> updated node" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Algorithm\n", "\n", "### insert\n", "\n", "* Append to the internal array.\n", "\n", "Complexity:\n", "* Time: O(1)\n", "* Space: O(1)\n", "\n", "### extract_min\n", "\n", "* Loop through each item in the internal array\n", " * Update the min value as needed\n", "* Remove the min element from the array and return it\n", "\n", "Complexity:\n", "* Time: O(n)\n", "* Space: O(1)\n", "\n", "### decrease_key\n", "\n", "* Loop through each item in the internal array to find the matching input\n", " * Update the matching element's key\n", "\n", "Complexity:\n", "* Time: O(n)\n", "* Space: O(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Code" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting priority_queue.py\n" ] } ], "source": [ "%%writefile priority_queue.py\n", "import sys\n", "\n", "\n", "class PriorityQueueNode(object):\n", "\n", " def __init__(self, obj, key):\n", " self.obj = obj\n", " self.key = key\n", "\n", " def __repr__(self):\n", " return str(self.obj) + ': ' + str(self.key)\n", "\n", "\n", "class PriorityQueue(object):\n", "\n", " def __init__(self):\n", " self.array = []\n", "\n", " def __len__(self):\n", " return len(self.array)\n", "\n", " def insert(self, node):\n", " self.array.append(node)\n", " return self.array[-1]\n", "\n", " def extract_min(self):\n", " if not self.array:\n", " return None\n", " minimum = sys.maxsize\n", " for index, node in enumerate(self.array):\n", " if node.key < minimum:\n", " minimum = node.key\n", " minimum_index = index\n", " return self.array.pop(minimum_index)\n", "\n", " def decrease_key(self, obj, new_key):\n", " for node in self.array:\n", " if node.obj is obj:\n", " node.key = new_key\n", " return node\n", " return None" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "%run priority_queue.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Unit Test" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting test_priority_queue.py\n" ] } ], "source": [ "%%writefile test_priority_queue.py\n", "import unittest\n", "\n", "\n", "class TestPriorityQueue(unittest.TestCase):\n", "\n", " def test_priority_queue(self):\n", " priority_queue = PriorityQueue()\n", " self.assertEqual(priority_queue.extract_min(), None)\n", " priority_queue.insert(PriorityQueueNode('a', 20))\n", " priority_queue.insert(PriorityQueueNode('b', 5))\n", " priority_queue.insert(PriorityQueueNode('c', 15))\n", " priority_queue.insert(PriorityQueueNode('d', 22))\n", " priority_queue.insert(PriorityQueueNode('e', 40))\n", " priority_queue.insert(PriorityQueueNode('f', 3))\n", " priority_queue.decrease_key('f', 2)\n", " priority_queue.decrease_key('a', 19)\n", " mins = []\n", " while priority_queue.array:\n", " mins.append(priority_queue.extract_min().key)\n", " self.assertEqual(mins, [2, 5, 15, 19, 22, 40])\n", " print('Success: test_min_heap')\n", "\n", "\n", "def main():\n", " test = TestPriorityQueue()\n", " test.test_priority_queue()\n", "\n", "\n", "if __name__ == '__main__':\n", " main()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success: test_min_heap\n" ] } ], "source": [ "%run -i test_priority_queue.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.7.2" } }, "nbformat": 4, "nbformat_minor": 1 }