BackendML

Binary Search

Easy3 min read
The Binary Search problem requires efficiently finding a target value in a sorted array by repeatedly reducing the search space by half.

Problem

Given a sorted array of integers nums and an integer target, return the index of target if it exists in the array. Otherwise, return -1.

The array is sorted in ascending order, and the algorithm should run in O(log n) time.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

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

Example 2

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

Solution

This solution uses Binary Search to find the target efficiently in the sorted array.

We maintain two pointers, left and right, representing the current search range. We calculate the middle index and compare the middle value with the target.

If the middle value equals the target, we return its index. If the middle value is smaller than the target, we search the right half. Otherwise, we search the left half.
class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
}
Binary Search can also be implemented using Recursion. The search range is passed to each recursive call, and approximately half of the remaining elements are eliminated at every step.

If left becomes greater than right, the search range is empty and the target does not exist in the array.
class Solution {
    public int search(int[] nums, int target) {
        return search(nums, 0, nums.length - 1, target);
    }

    public int search(int[] nums, int left, int right, int target) {
        if (left > right) {
            return -1;
        }

        int mid = left + (right - left) / 2;

        if (nums[mid] == target) {
            return mid;
        }

        if (target < nums[mid]) {
            return search(nums, left, mid - 1, target);
        } else {
            return search(nums, mid + 1, right, target);
        }
    }
}

Complexity

For both approaches, each step eliminates approximately half of the search space, so the time complexity is O(log n).

The iterative approach uses O(1) extra space. The recursive approach uses O(log n) space because of the recursion call stack.
The Search Insert Position problem requires finding the index of a target value in a sorted array. If the target does not exist, return the index where it should be inserted to maintain the sorted order.

It uses the same Binary Search technique.

If the target is not found, instead of returning -1, we return the left pointer because, when the search ends, all elements before left are smaller than the target, while all elements from left onward are greater than or equal to the target.

Therefore, left is the correct insertion position.

Comments

No comments yet. Ask a question or share what helped.