Taro Logo

Binary Search

Hard
12 years ago

Okay, for this first question, I'd like you to implement a binary search algorithm. The binary search algorithm is a search algorithm that finds the position of a target value within a sorted array. It works by repeatedly dividing the search interval in half. If the middle element is the target, then the index is returned. If the target is less than the middle element, then the search continues in the left half. If the target is greater than the middle element, then the search continues in the right half. This process repeats until the target is found or the interval is empty.

Write a function binarySearch(arr, target) that takes a sorted array arr and a target value target as input, and returns the index of the target value in the array if it exists, or -1 if it does not exist.

Here are some examples to illustrate the expected behavior:

  • binarySearch([2, 5, 7, 8, 11, 12], 13) should return -1
  • binarySearch([2, 5, 7, 8, 11, 12], 12) should return 5
  • binarySearch([2, 5, 7, 8, 11, 12], 0) should return -1
  • binarySearch([1, 2, 3, 4, 5, 6], 4) should return 3
  • binarySearch([-1, 0, 3, 5, 9, 12], 9) should return 4
  • binarySearch([-1, 0, 3, 5, 9, 12], 2) should return -1
Sample Answer

Binary Search

Binary search is an efficient algorithm for finding a target value within a sorted array. It works by repeatedly dividing the search interval in half. If the middle element is the target, the search is successful. If the target is less than the middle element, the search continues in the left half. If the target is greater than the middle element, the search continues in the right half. This process continues until the target is found or the search interval is empty.

1. Naive (Brute Force) Solution

While binary search is already an efficient approach, let's consider a less optimal, brute-force perspective, not because we would use it, but to highlight the improvements binary search provides. Imagine we simply iterate through the sorted array, comparing each element to the target value.

python def linear_search(arr, target): for i in range(len(arr)): if arr[i] == target: return i return -1 # Target not found

This approach has a time complexity of O(n), where n is the number of elements in the array, because in the worst case, we might have to check every element. Its space complexity is O(1), as we only use a constant amount of extra space.

2. Optimal Solution (Binary Search)

The optimal solution is the binary search algorithm itself.

python def binary_search(arr, target): left = 0 right = len(arr) - 1

while left <= right:
    mid = (left + right) // 2  # Integer division to find the middle index

    if arr[mid] == target:
        return mid  # Target found
    elif arr[mid] < target:
        left = mid + 1  # Search in the right half
    else:
        right = mid - 1  # Search in the left half

return -1  # Target not found

3. Big(O) Run-time

Binary search has a time complexity of O(log n), where n is the number of elements in the sorted array. This is because the search space is halved in each iteration.

4. Big(O) Space Usage

Binary search has a space complexity of O(1), as it uses a constant amount of extra space regardless of the size of the input array.

5. Edge Cases

  • Empty Array: If the input array is empty, the algorithm should return -1, indicating that the target is not found.
  • Target at the Beginning or End: The algorithm should correctly identify the target if it's located at the beginning or end of the array.
  • Target Not Present: The algorithm should return -1 if the target is not present in the array.
  • Large Arrays: The algorithm should handle large arrays efficiently without causing stack overflow or other issues.
  • Duplicate Values: If the array contains duplicate values, the algorithm may return any index where the target is found. If a specific index is needed (e.g., the first occurrence), the algorithm needs to be modified accordingly.

6. Code (Python)

The code is presented above in the 'Optimal Solution' section.