Binary Search - Problem
Binary Search is a fundamental algorithm for efficiently finding a target value in a sorted array. Given an array of integers
nums sorted in ascending order and an integer target, your task is to write a function that searches for the target in the array. If the target exists, return its index position. If it doesn't exist, return -1. The challenge is to achieve this with O(log n) runtime complexity, making it much faster than a simple linear search. This algorithm works by repeatedly dividing the search space in half, eliminating half of the remaining elements at each step. Input & Output
example_1.py โ Standard Case
$
Input:
nums = [-1,0,3,5,9,12], target = 9
โบ
Output:
4
๐ก Note:
The target 9 exists in the array at index 4, so we return 4.
example_2.py โ Target Not Found
$
Input:
nums = [-1,0,3,5,9,12], target = 2
โบ
Output:
-1
๐ก Note:
The target 2 does not exist in the array, so we return -1.
example_3.py โ Single Element
$
Input:
nums = [5], target = 5
โบ
Output:
0
๐ก Note:
The array has only one element which matches the target, so we return index 0.
Visualization
Tap to expand
Understanding the Visualization
1
Set Boundaries
Initialize left=0, right=length-1 to define search space
2
Find Middle
Calculate mid = left + (right-left)/2 to avoid overflow
3
Compare and Eliminate
If target > middle, search right half; if target < middle, search left half
4
Repeat or Return
Continue until target found or search space exhausted
Key Takeaway
๐ฏ Key Insight: Binary search achieves O(log n) complexity by eliminating half the search space with each comparison, making it exponentially faster than linear search for large sorted arrays.
Time & Space Complexity
Time Complexity
O(log n)
We eliminate half of the search space at each step, leading to logarithmic time complexity
โก Linearithmic
Space Complexity
O(1)
Only using a constant amount of extra space for pointers
โ Linear Space
Constraints
- 1 โค nums.length โค 104
- -104 < nums[i], target < 104
- All integers in nums are unique
- nums is sorted in ascending order
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code