{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

704. Binary Search

\n", "
\n", "\n", "\n", "

Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.

\n", "\n", "


\n", "Example 1:

\n", "\n", "
Input: nums = [-1,0,3,5,9,12], target = 9\n",
    "Output: 4\n",
    "Explanation: 9 exists in nums and its index is 4\n",
    "\n",
    "
\n", "\n", "

Example 2:

\n", "\n", "
Input: nums = [-1,0,3,5,9,12], target = 2\n",
    "Output: -1\n",
    "Explanation: 2 does not exist in nums so return -1\n",
    "
\n", "\n", "

 

\n", "\n", "

Note:

\n", "\n", "
    \n", "\t
  1. You may assume that all elements in nums are unique.
  2. \n", "\t
  3. n will be in the range [1, 10000].
  4. \n", "\t
  5. The value of each element in nums will be in the range [-9999, 9999].
  6. \n", "
\n", "\n", "\n", "

 

\n", "Source \n", "
\n", "\n", "

Code

" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def binary_search(nums, target):\n", " \"\"\"Iterative implementation of binary search\"\"\"\n", " left = 0\n", " right = len(nums)-1\n", " while left <= right:\n", " mid = (left + right) // 2\n", " if nums[mid] == target:\n", " return mid\n", " if nums[mid] < target:\n", " left = mid+1\n", " if target < nums[mid]:\n", " right = mid-1\n", " return -1" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def binary_search(nums, target):\n", " \"\"\"Alternative version of above solution\"\"\"\n", " left = 0\n", " right = len(nums) # vs. len(nums)-1\n", " while left < right: # vs. <=\n", " mid = (left + right) // 2\n", " if nums[mid] == target:\n", " return mid\n", " if nums[mid] < target:\n", " left = mid+1\n", " if target < nums[mid]:\n", " right = mid # vs. mid-1\n", " return -1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Check

" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nums = [-1,0,3,5,9,12]\n", "target = 9\n", "binary_search(nums, target)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nums = [-1,0,3,5,9,12]\n", "target = 2\n", "binary_search(nums, target)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Follow up:

\n", "

Solve it both iteratively and recursively. Solve it using built-in methods too.

" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "def binary_search(nums, target):\n", " \"\"\"Recursive implementation of binary search\"\"\"\n", " def helper(left, right):\n", " if right < left: # base case: target not present\n", " return -1\n", "\n", " nonlocal nums, target\n", " mid = left + (right-left)//2\n", "\n", " if nums[mid] == target: # base case: target at middle index\n", " return mid\n", " if target > nums[mid]:\n", " return helper(mid+1, right)\n", " else:\n", " return helper(left, mid-1)\n", "\n", "\n", "\n", " return helper(0, len(nums)-1)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def binary_search(nums, target):\n", " \"\"\"Using Built-in method index()\"\"\"\n", " try:\n", " return nums.index(target)\n", " except ValueError: # index() returns an error if target is not in nums\n", " return -1" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "from bisect import bisect_left\n", "\n", "def binary_search(nums, target):\n", " \"\"\"Using Built-in method bisect_left()\"\"\"\n", " i = bisect_left(nums, target) \n", " return i if i != len(nums) and nums[i] == target else -1 " ] } ], "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.8.2" } }, "nbformat": 4, "nbformat_minor": 1 }