Binary Search
LeetCode 704 · Easy · solution, intuition & step-by-step walkthrough
Halve [low, high] around mid until found or empty.
This is how I solved Binary Search (LeetCode 704), an easy problem from the Basics / Lower & Upper Bound pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
In a sorted array, comparing the target with the middle element rules out half of the remaining range every step.
Approach
- 1
low = 0, high = n − 1.
- 2
mid = (low + high) // 2.
- 3
Equal → return mid; target bigger → low = mid + 1; smaller → high = mid − 1.
- 4
Empty range → −1.
How I solved it
Iterative binary searchPythonO(log n) time · O(1) space
class Solution:
def search(self, nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target == nums[mid]:
return mid
if target > nums[mid]:
low = mid + 1
else:
high = mid - 1
return -1Binary Search — FAQ
What is the intuition behind Binary Search?
In a sorted array, comparing the target with the middle element rules out half of the remaining range every step.
How do you solve Binary Search (LeetCode 704)?
1. low = 0, high = n − 1. 2. mid = (low + high) // 2. 3. Equal → return mid; target bigger → low = mid + 1; smaller → high = mid − 1. 4. Empty range → −1.
What is the time and space complexity of Binary Search?
Time: O(log n). Space: O(1). (Accepted approach: Iterative binary search.)
What are common mistakes in Binary Search?
Use low ≤ high so single-element ranges are checked.