Skip to content
PlaceNivo

Binary Search Easy

Binary Search: Solution and Approach

Given a sorted array and a target, return the index of the target, or -1 if it is not in the array. The solution must run in O(log n).

Similar questions reported in: TCS, Wipro, Capgemini, Accenture, Cognizant

Example

Input:
nums = [-1, 0, 3, 5, 9, 12], target = 9
Output:
4

Brute force first

Scan from left to right: O(n).

The better idea

Compare the target with the middle element. Because the array is sorted, you can throw away the half that can't contain the target, and halve the search space each step.

Steps

  1. Set low = 0 and high = n - 1.
  2. While low <= high: mid = low + (high - low) / 2.
  3. If nums[mid] equals the target, return mid. If it is smaller, set low = mid + 1. Otherwise set high = mid - 1.
  4. Return -1 when the loop ends.

Code

def search(nums, target):
    low, high = 0, len(nums) - 1
    while low <= high:
        mid = (low + high) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

Complexity

Time: O(log n)

Space: O(1)

Edge cases to test

  • The target is smaller than every element or larger than every element.
  • Write mid = low + (high - low) / 2 to avoid integer overflow in Java and C++.

Solved it? Pick the next problem

Do one more problem from the same pattern today, so the idea sticks.