1 minute read

704. Binary Search

Difficulty: Easy

Related Topics: Array, Binary Search

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

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

Example 2:

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

First Attempt:

Code:

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        def binarySearch(temp, target):
            if nums[temp] == target:
                return temp
            elif nums[temp] < target:
                temp = int(temp+((len(nums)-temp)/2))
                return binarySearch(temp, target)
            elif nums[temp] > target:
                temp = int(temp / 2)
                return binarySearch(temp, target)

        if target not in nums:
            return -1
        temp = int(len(nums) / 2)
        answer = binarySearch(temp, target)
        return answer

Feedbacks:

I tried out this code without any basics of binarySearch and I got maximum recursion depth exceed error. And I am also confused of line of codes which find there is no target number in the list.

Second Attempt:

Code:

 class Solution:
    def search(self, nums: List[int], target: int) -> int:
        right = len(nums) - 1
        left = 0
        while left <= right:
            mid = int((left+right)//2)
            if nums[mid]==target: return mid
            if nums[mid]<target: left = mid+1
            else: right = mid-1
        return -1

Feedbacks:

I tried to figure out error on first attempt code, but I couldn’t so I got some help on other answers with explanation. It was surprising that binarysearch does not use recursion. Shocked me a little. Now, I fully understood the algorithm of binary search. I am looking forward to other binary search problems also!