Binary Search - Leetcode Solution


Step-by-Step Thought Process

Brute Force

  1. Understand the problem: Find the index of a target value in a sorted array, or return -1 if it doesn't exist.
  2. Iterate through each index i from 0 to the length of the array minus 1.
  3. Check if the element at index i equals the target.
  4. If a match is found, return the index i.
  5. If no match is found after the loop, return -1.

Code Solution (Brute Force)


                

                

                

                

Why the Brute-Force Solution is Inefficient

The brute-force solution checks every element in the array sequentially, ignoring the fact that the array is sorted, leading to:

Optimal Solution

The optimal solution uses binary search to exploit the sorted array, achieving O(log n) time complexity:

  1. Initialize two pointers, left to 0 and right to the array length minus 1.
  2. While left is less than or equal to right, compute the middle index as the average of left and right.
  3. If the middle element equals the target, return the middle index.
  4. If the middle element is greater than the target, adjust right to middle - 1 to search the left half.
  5. If the middle element is less than the target, adjust left to middle + 1 to search the right half.
  6. If the target is not found, return -1.

Code Solution (Optimal)


                

                

                

                

Detailed Explanation

Understanding the Problem: Binary Search

The “Binary Search” problem is one of the most fundamental and efficient search algorithms. Given a sorted array and a target value, your task is to determine whether the target exists in the array, and if so, return its index. If the target does not exist, return -1.

Example:

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

Why This Problem Matters

Binary search is a cornerstone of algorithmic thinking. It's widely used because of its efficiency — reducing the time complexity from O(n) in a linear search to O(log n). Mastering binary search is essential for understanding other advanced algorithms like binary search trees, search-related dynamic programming, and range-based queries.

Optimal Approach: Binary Search on a Sorted Array

Binary search works by repeatedly dividing the search range in half. If the middle element is equal to the target, we return its index. Otherwise, we eliminate half of the remaining elements by comparing the middle value to the target.

Steps:

  1. Initialize two pointers: left = 0 and right = nums.length - 1.
  2. While left <= right:
    • Compute the middle index: mid = Math.floor((left + right) / 2)
    • If nums[mid] == target, return mid.
    • If nums[mid] > target, move the search to the left: right = mid - 1.
    • If nums[mid] < target, move the search to the right: left = mid + 1.
  3. If the loop ends, the target is not in the array. Return -1.

Example Walkthrough

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

  • left = 0, right = 5 → mid = 2 → nums[2] = 3 → target > 3 → left = 3
  • left = 3, right = 5 → mid = 4 → nums[4] = 9 → match → return 4

Time and Space Complexity

Time Complexity: O(log n), because each iteration cuts the search space in half.
Space Complexity: O(1), as the algorithm only uses a fixed amount of memory.

Edge Cases to Consider

  • Empty array → return -1 immediately
  • Single-element array → check that element directly
  • Target not in array → return -1
  • Target at the first or last index → ensure boundaries are handled correctly

Conclusion

The “Binary Search” problem showcases the power of divide-and-conquer algorithms. It’s simple, elegant, and efficient — making it a critical concept for solving complex problems efficiently. Knowing when and how to use binary search is an essential tool in every programmer’s toolbox.

Get Personalized Support at AlgoMap Bootcamp 💡