{ "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 the magic index in an array, where array[i] = i.\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 array sorted?\n", " * Yes\n", "* Are the elements in the array distinct?\n", " * No\n", "* Does a magic index always exist?\n", " * No\n", "* If there is no magic index, do we just return -1?\n", " * Yes\n", "* Are negative values allowed in the array?\n", " * Yes\n", "* If there are multiple magic values, what do we return?\n", " * Return the left-most one\n", "* Can we assume this fits memory?\n", " * Yes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Test Cases\n", "\n", "* None input -> -1\n", "* Empty array -> -1\n", "\n", "
\n",
    "a[i]  -4 -2  2  6  6  6  6 10\n",
    "  i    0  1  2  3  4  5  6  7\n",
    "
\n", "\n", "Result: 2\n", "\n", "
\n",
    "a[i]  -4 -2  1  6  6  6  6 10\n",
    "  i    0  1  2  3  4  5  6  7\n",
    "
\n", "\n", "Result: 6\n", "\n", "
\n",
    "a[i]  -4 -2  1  6  6  6  7 10\n",
    "  i    0  1  2  3  4  5  6  7\n",
    "
\n", "\n", "Result: -1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Algorithm\n", "\n", "We'll use a binary search to split the search space in half on each iteration. To obtain more efficiency, we can do a little better than a naive left and half split.\n", "\n", "In the example below, we see that i == 5 cannot be the magic index, otherwise a[5] would have to equal 5 (note a[4] == 6).\n", "\n", "
\n",
    "a[i]  -4 -2  2  6  6  6  6 10\n",
    "  i    0  1  1  3  4  5  6  7\n",
    "                  mid\n",
    "
\n", "\n", "Similarly, in the example below we can further trim the left search space.\n", "\n", "
\n",
    "a[i]  -4 -2  2  2  2  6  6 10\n",
    "  i    0  1  2  3  4  5  6  7\n",
    "                  mid\n",
    "
\n", "\n", "\n", "* Calculate mid\n", "* If mid == array[mid], return mid\n", "* Recurse on the left side of the array\n", " * start: 0\n", " * end: min(mid-1, array[mid]\n", "* Recurse on the right side of the array\n", " * start: max(mid+1, array[mid]\n", " * end: end\n", "\n", "Complexity:\n", "* Time: O(log(n))\n", "* Space: O(log(n))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Code" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from __future__ import division\n", "\n", "\n", "class MagicIndex(object):\n", "\n", " def find_magic_index(self, array):\n", " if array is None or not array:\n", " return -1\n", " return self._find_magic_index(array, 0, len(array) - 1)\n", "\n", " def _find_magic_index(self, array, start, end):\n", " if end < start or start < 0 or end >= len(array):\n", " return -1\n", " mid = (start + end) // 2\n", " if mid == array[mid]:\n", " return mid\n", " left_end = min(mid - 1, array[mid])\n", " left_result = self._find_magic_index(array, start, end=left_end)\n", " if left_result != -1:\n", " return left_result\n", " right_start = max(mid + 1, array[mid])\n", " right_result = self._find_magic_index(array, start=right_start, end=end)\n", " if right_result != -1:\n", " return right_result\n", " return -1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Unit Test" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting test_find_magic_index.py\n" ] } ], "source": [ "%%writefile test_find_magic_index.py\n", "import unittest\n", "\n", "\n", "class TestFindMagicIndex(unittest.TestCase):\n", "\n", " def test_find_magic_index(self):\n", " magic_index = MagicIndex()\n", " self.assertEqual(magic_index.find_magic_index(None), -1)\n", " self.assertEqual(magic_index.find_magic_index([]), -1)\n", " array = [-4, -2, 2, 6, 6, 6, 6, 10]\n", " self.assertEqual(magic_index.find_magic_index(array), 2)\n", " array = [-4, -2, 1, 6, 6, 6, 6, 10]\n", " self.assertEqual(magic_index.find_magic_index(array), 6)\n", " array = [-4, -2, 1, 6, 6, 6, 7, 10]\n", " self.assertEqual(magic_index.find_magic_index(array), -1)\n", " print('Success: test_find_magic')\n", "\n", "\n", "def main():\n", " test = TestFindMagicIndex()\n", " test.test_find_magic_index()\n", "\n", "\n", "if __name__ == '__main__':\n", " main()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success: test_find_magic\n" ] } ], "source": [ "%run -i test_find_magic_index.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 }