Binary Search

Program for Binary Search Problem

You are given a list of unique numbers arranged in increasing order and a specific number called target.

Your task is to create a function that looks for the target in this list. If the target is found, return its position (index) in the list. If it’s not found, return -1.

The function should be efficient and complete the search in O(log n) time, meaning it should use a method like binary search that quickly narrows down the possible locations of the target.

Binary Search Problem

Constraints:

  • 1 <= nums.length <= 10000.
  • -10000 < nums[i], target < 10000

Program for Binary Search Solution

Recommendation for Time and Space Complexity –You should aim for a solution with O(logn) time and O(1) space, where n is the size of the input array.

Hints for solving problems

Hint 1 :

Can you find an algorithm that is useful when the array is sorted? Maybe other than linear search.

Hint 2 :

The problem name is the name of the algorithm that we can use. We need to find a target value and if it does not exist in the array return -1. We have l and r as the boundaries of the segment of the array in which we are searching. Try building conditions to eliminate half of the search segment at each step. Maybe sorted nature of the array can be helpful.

There are mainly 5 approach to solve this problem-

  1. Recursive Binary Search Method
  2. Iterative Binary Search Method
  3. Upper Bound Method
  4. Lower Bound Method
  5. Built-in Tool Method

1. Recursive Binary Search Method

Use a recursive function to repeatedly divide the search range in half until the target is found or the range becomes empty.

  • Time complexity: O(log n)
  • Space complexity: O(log n)

Code

2. Iterative Binary Search Method

Use a loop to perform binary search by adjusting the left and right pointers until the target is located or the search range is exhausted.

  • Time complexity: O(log n)
  • Space complexity: O(1)

Code

3. Upper Bound Method

Find the smallest index where the target could be inserted without changing the order, focusing on the upper limit of the target’s position.

  • Time complexity: O(log n)
  • Space complexity: O(1)

Code

4. Lower Bound Method

Find the first index where the target could appear, identifying the lower limit of its position in the sorted list.

  • Time complexity: O(log n)
  • Space complexity: O(1)

Code

5. Built-in Tool Method

Use built-in functions like Python’s bisect module to perform binary search efficiently with minimal code.

  • Time complexity: O(log n)
  • Space complexity: O(1)

Code

More Articles