Add rotated array search challenge

This commit is contained in:
Donne Martin 2017-03-27 05:14:53 -04:00
parent 1208e1110f
commit 256755a962
4 changed files with 467 additions and 0 deletions

View File

@ -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
}

View File

@ -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",
"<pre>\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",
"</pre>\n",
"\n",
"### General case with dupes\n",
"\n",
"<pre>\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",
"</pre>\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
}

View File

@ -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()