"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",
"<pre>\n",
"a[i] -4 -2 2 6 6 6 6 10\n",
" i 0 1 2 3 4 5 6 7\n",
"</pre>\n",
"\n",
"Result: 2\n",
"\n",
"<pre>\n",
"a[i] -4 -2 1 6 6 6 6 10\n",
" i 0 1 2 3 4 5 6 7\n",
"</pre>\n",
"\n",
"Result: 6\n",
"\n",
"<pre>\n",
"a[i] -4 -2 1 6 6 6 7 10\n",
" i 0 1 2 3 4 5 6 7\n",
"</pre>\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",
"<pre>\n",
"a[i] -4 -2 2 6 6 6 6 10\n",
" i 0 1 1 3 4 5 6 7\n",
" mid\n",
"</pre>\n",
"\n",
"Similarly, in the example below we can further trim the left search space.\n",