KatInterview

792. Binary Search

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find a target value within a sorted array of unique integers. The key constraint is that the solution must have a time complexity of O(log n). This requirement immediately points to the classic Binary Search algorithm, which is highly efficient for searching in sorted data structures.

Solution

Binary Search in Python

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left, right = 0, len(nums) - 1

        # Loop continues as long as the search space [left, right] is valid
        while left <= right:
            # Calculate mid point. In Python, standard integers don't overflow,
            # but this formula is a good practice. `//` is integer division.
            mid = left + (right - left) // 2
            
            if nums[mid] == target:
                # Target found, return its index
                return mid
            elif nums[mid] < target:
                # Target is in the right half, discard the left half
                left = mid + 1
            else: # nums[mid] > target
                # Target is in the left half, discard the right half
                right = mid - 1
        
        # Target not found in the array
        return -1

Binary Search in Java

class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1; // Initialize right pointer to the last index

        // Loop continues as long as the search space [left, right] is valid
        while (left <= right) {
            // Calculate mid point to avoid potential integer overflow
            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                // Target found, return its index
                return mid;
            } else if (nums[mid] < target) {
                // Target is in the right half, discard the left half
                left = mid + 1;
            } else { // nums[mid] > target
                // Target is in the left half, discard the right half
                right = mid - 1;
            }
        }

        // Target not found in the array
        return -1;
    }
}

Binary Search in C++

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int left = 0;
        int right = nums.size() - 1; // Initialize right pointer to the last index

        // Loop continues as long as the search space [left, right] is valid
        while (left <= right) {
            // Calculate mid point to avoid potential integer overflow
            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                // Target found, return its index
                return mid;
            } else if (nums[mid] < target) {
                // Target is in the right half, discard the left half
                left = mid + 1;
            } else { // nums[mid] > target
                // Target is in the left half, discard the right half
                right = mid - 1;
            }
        }

        // Target not found in the array
        return -1;
    }
};

Binary Search in TypeScript

function search(nums: number[], target: number): number {
    let left: number = 0;
    let right: number = nums.length - 1; // Initialize right pointer to the last index

    // Loop continues as long as the search space [left, right] is valid
    while (left <= right) {
        // Calculate mid point to avoid potential overflow and use floor for integer index
        const mid = Math.floor(left + (right - left) / 2);

        if (nums[mid] === target) {
            // Target found, return its index
            return mid;
        } else if (nums[mid] < target) {
            // Target is in the right half, discard the left half
            left = mid + 1;
        } else { // nums[mid] > target
            // Target is in the left half, discard the right half
            right = mid - 1;
        }
    }

    // Target not found in the array
    return -1;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.