From 256755a9628b61069426915f78f98449dc8415ab Mon Sep 17 00:00:00 2001 From: Donne Martin Date: Mon, 27 Mar 2017 05:14:53 -0400 Subject: [PATCH] Add rotated array search challenge --- .../rotated_array_search/__init__.py | 0 .../rotated_array_search_challenge.ipynb | 175 ++++++++++++ .../rotated_array_search_solution.ipynb | 268 ++++++++++++++++++ .../test_search_sorted_array.py | 24 ++ 4 files changed, 467 insertions(+) create mode 100644 sorting_searching/rotated_array_search/__init__.py create mode 100644 sorting_searching/rotated_array_search/rotated_array_search_challenge.ipynb create mode 100644 sorting_searching/rotated_array_search/rotated_array_search_solution.ipynb create mode 100644 sorting_searching/rotated_array_search/test_search_sorted_array.py diff --git a/sorting_searching/rotated_array_search/__init__.py b/sorting_searching/rotated_array_search/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sorting_searching/rotated_array_search/rotated_array_search_challenge.ipynb b/sorting_searching/rotated_array_search/rotated_array_search_challenge.ipynb new file mode 100644 index 0000000..2ea3ae2 --- /dev/null +++ b/sorting_searching/rotated_array_search/rotated_array_search_challenge.ipynb @@ -0,0 +1,175 @@ +{ + "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": [ + "# Challenge Notebook" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Problem: Find an element in a sorted array that has been rotated a number of times.\n", + "\n", + "* [Constraints](#Constraints)\n", + "* [Test Cases](#Test-Cases)\n", + "* [Algorithm](#Algorithm)\n", + "* [Code](#Code)\n", + "* [Unit Test](#Unit-Test)\n", + "* [Solution Notebook](#Solution-Notebook)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Constraints\n", + "\n", + "* Is the input an array of ints?\n", + " * Yes\n", + "* Do we know how many times the array was rotated?\n", + " * No\n", + "* Was the array originally sorted in increasing or decreasing order?\n", + " * Increasing\n", + "* For the output, do we return the index?\n", + " * Yes\n", + "* Can we assume the inputs are valid?\n", + " * No\n", + "* Can we assume this fits memory?\n", + " * Yes" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Test Cases\n", + "\n", + "* None -> Exception\n", + "* [] -> None\n", + "* Not found -> None\n", + "* General case with duplicates\n", + "* General case without duplicates" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Algorithm\n", + "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Code" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Array(object):\n", + "\n", + " def search_sorted_array(self, array, val):\n", + " # TODO: Implement me\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Unit Test" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**The following unit test is expected to fail until you solve the challenge.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# %load test_search_sorted_array.py\n", + "from nose.tools import assert_equal, assert_raises\n", + "\n", + "\n", + "class TestArray(object):\n", + "\n", + " def test_search_sorted_array(self):\n", + " array = Array()\n", + " assert_raises(TypeError, array.search_sorted_array, None)\n", + " assert_equal(array.search_sorted_array([3, 1, 2], 0), None)\n", + " assert_equal(array.search_sorted_array([3, 1, 2], 0), None)\n", + " data = [10, 12, 14, 1, 3, 5, 6, 7, 8, 9]\n", + " assert_equal(array.search_sorted_array(data, val=1), 3)\n", + " data = [ 1, 1, 2, 1, 1, 1, 1, 1, 1, 1]\n", + " assert_equal(array.search_sorted_array(data, val=2), 2)\n", + " print('Success: test_search_sorted_array')\n", + "\n", + "\n", + "def main():\n", + " test = TestArray()\n", + " test.test_search_sorted_array()\n", + "\n", + "\n", + "if __name__ == '__main__':\n", + " main()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Solution Notebook\n", + "\n", + "Review the [Solution Notebook]() for a discussion on algorithms and code solutions." + ] + } + ], + "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 +} diff --git a/sorting_searching/rotated_array_search/rotated_array_search_solution.ipynb b/sorting_searching/rotated_array_search/rotated_array_search_solution.ipynb new file mode 100644 index 0000000..6167b72 --- /dev/null +++ b/sorting_searching/rotated_array_search/rotated_array_search_solution.ipynb @@ -0,0 +1,268 @@ +{ + "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: Find an element in a sorted array that has been rotated a number of times.\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 array of ints?\n", + " * Yes\n", + "* Can the input have duplicates?\n", + " * Yes\n", + "* Do we know how many times the array was rotated?\n", + " * No\n", + "* Was the array originally sorted in increasing or decreasing order?\n", + " * Increasing\n", + "* For the output, do we return the index?\n", + " * Yes\n", + "* Can we assume the inputs are valid?\n", + " * No\n", + "* Can we assume this fits memory?\n", + " * Yes" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Test Cases\n", + "\n", + "* None -> Exception\n", + "* [] -> None\n", + "* Not found -> None\n", + "* General case with duplicates\n", + "* General case without duplicates" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Algorithm\n", + "\n", + "### General case without dupes\n", + "\n", + "
\n",
+    "\n",
+    "index                   0   1   2   3   4   5   6   7   8   9\n",
+    "input                 [ 1,  3,  5,  6,  7,  8,  9, 10, 12, 14]\n",
+    "input rotated 1x      [10, 12, 14,  1,  3,  5,  6,  7,  8,  9]\n",
+    "input rotated 2x      [ 5,  6,  7,  8,  9, 10, 12, 14,  1,  3]\n",
+    "input rotated 3x      [10, 12, 14,  1,  3,  5,  6,  7,  8,  9]\n",
+    "\n",
+    "find 1\n",
+    "len = 10\n",
+    "mid = 10 // 2 = 5\n",
+    "                        s                   m               e\n",
+    "index                   0   1   2   3   4   5   6   7   8   9\n",
+    "input                 [10, 12, 14,  1,  3,  5,  6,  7,  8,  9]\n",
+    "\n",
+    "input[start] > input[mid]: Left half is rotated\n",
+    "input[end] >= input[mid]: Right half is sorted\n",
+    "1 is not within input[mid+1] to input[end] on the right side, go left\n",
+    "\n",
+    "                        s       m       e\n",
+    "index                   0   1   2   3   4   5   6   7   8   9\n",
+    "input                 [10, 12, 14,  1,  3,  5,  6,  7,  8,  9]\n",
+    "\n",
+    "input[start] <= input[mid]: Right half is rotated\n",
+    "input[end] >= input[mid]: Left half is sorted\n",
+    "1 is not within input[left] to input[mid-1] on the left side, go right\n",
+    "\n",
+    "
\n", + "\n", + "### General case with dupes\n", + "\n", + "
\n",
+    "\n",
+    "                        s                   m               e\n",
+    "index                   0   1   2   3   4   5   6   7   8   9\n",
+    "input                 [ 1,  1,  1,  1,  1,  1,  1,  1,  1,  2]\n",
+    "\n",
+    "input[start] == input[mid], input[mid] != input[end], go right\n",
+    "\n",
+    "input rotated 1x      [ 1,  1,  2,  1,  1,  1,  1,  1,  1,  1]\n",
+    "\n",
+    "input[start] == input[mid] == input[end], search both sides\n",
+    "\n",
+    "
\n", + "\n", + "Complexity:\n", + "* Time: O(log n) if there are no duplicates, else O(n)\n", + "* Space: O(m), where m is the recursion depth" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Code" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Array(object):\n", + "\n", + " def search_sorted_array(self, array, val):\n", + " if array is None or val is None:\n", + " raise TypeError('array or val cannot be None')\n", + " if not array:\n", + " return None\n", + " return self._search_sorted_array(array, val, start=0, end=len(array) - 1)\n", + "\n", + " def _search_sorted_array(self, array, val, start, end):\n", + " if end < start:\n", + " return None\n", + " mid = (start + end) // 2\n", + " if array[mid] == val:\n", + " return mid\n", + " # Left side is sorted\n", + " if array[start] < array[mid]:\n", + " if array[start] <= val < array[mid]:\n", + " return self._search_sorted_array(array, val, start, mid - 1)\n", + " else:\n", + " return self._search_sorted_array(array, val, mid + 1, end)\n", + " # Right side is sorted\n", + " elif array[start] > array[mid]:\n", + " if array[mid] < val <= array[end]:\n", + " return self._search_sorted_array(array, val, mid + 1, end)\n", + " else:\n", + " return self._search_sorted_array(array, val, start, mid - 1)\n", + " # Duplicates\n", + " else:\n", + " if array[mid] != array[end]:\n", + " return self._search_sorted_array(array, val, mid + 1, end)\n", + " else:\n", + " result = self._search_sorted_array(array, val, start, mid - 1)\n", + " if result != None:\n", + " return result\n", + " else:\n", + " return self._search_sorted_array(array, val, mid + 1, end)" + ] + }, + { + "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_search_sorted_array.py\n" + ] + } + ], + "source": [ + "%%writefile test_search_sorted_array.py\n", + "from nose.tools import assert_equal, assert_raises\n", + "\n", + "\n", + "class TestArray(object):\n", + "\n", + " def test_search_sorted_array(self):\n", + " array = Array()\n", + " assert_raises(TypeError, array.search_sorted_array, None)\n", + " assert_equal(array.search_sorted_array([3, 1, 2], 0), None)\n", + " assert_equal(array.search_sorted_array([3, 1, 2], 0), None)\n", + " data = [10, 12, 14, 1, 3, 5, 6, 7, 8, 9]\n", + " assert_equal(array.search_sorted_array(data, val=1), 3)\n", + " data = [ 1, 1, 2, 1, 1, 1, 1, 1, 1, 1]\n", + " assert_equal(array.search_sorted_array(data, val=2), 2)\n", + " print('Success: test_search_sorted_array')\n", + "\n", + "\n", + "def main():\n", + " test = TestArray()\n", + " test.test_search_sorted_array()\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_search_sorted_array\n" + ] + } + ], + "source": [ + "%run -i test_search_sorted_array.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.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/sorting_searching/rotated_array_search/test_search_sorted_array.py b/sorting_searching/rotated_array_search/test_search_sorted_array.py new file mode 100644 index 0000000..cf5229a --- /dev/null +++ b/sorting_searching/rotated_array_search/test_search_sorted_array.py @@ -0,0 +1,24 @@ +from nose.tools import assert_equal, assert_raises + + +class TestArray(object): + + def test_search_sorted_array(self): + array = Array() + assert_raises(TypeError, array.search_sorted_array, None) + assert_equal(array.search_sorted_array([3, 1, 2], 0), None) + assert_equal(array.search_sorted_array([3, 1, 2], 0), None) + data = [10, 12, 14, 1, 3, 5, 6, 7, 8, 9] + assert_equal(array.search_sorted_array(data, val=1), 3) + data = [ 1, 1, 2, 1, 1, 1, 1, 1, 1, 1] + assert_equal(array.search_sorted_array(data, val=2), 2) + print('Success: test_search_sorted_array') + + +def main(): + test = TestArray() + test.test_search_sorted_array() + + +if __name__ == '__main__': + main() \ No newline at end of file