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
Binary Search VisualizationTarget: 9-100132MID5394FOUND!125Search Process:1. Compare target (9) with middle element (3)2. Since 9 > 3, eliminate left half (red area)3. Search in right half (green area): [5, 9, 12]4. New middle is 9 - matches target!5. Return index 4EliminatedSearch Space
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

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using a constant amount of extra space for pointers

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • -104 < nums[i], target < 104
  • All integers in nums are unique
  • nums is sorted in ascending order
Asked in
Google 127 Amazon 89 Microsoft 76 Meta 52
98.4K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen