Binary Search
Master this topic with zero to advance depth.
Binary Search
Given a sorted array of integers nums and a target value target, return the index of target if it exists. Otherwise, return -1. You must write an algorithm with runtime complexity.
Examples
9 exists at index 4.
2 does not exist in the array.
Level I: Brute Force (Linear Scan)
Intuition
The most basic way to find a target is to check every element one by one. While simple, it fails to exploit the 'sorted' property of the input.
Detailed Dry Run
| Step | Index | Value | Match? |
|---|---|---|---|
| 1 | 0 | -1 | No |
| 2 | 1 | 0 | No |
| 3 | 2 | 3 | No |
| 4 | 3 | 5 | No |
| 5 | 4 | 9 | Yes (Return 4) |
Level II: Recursive Binary Search
Intuition
Binary search naturally follows a 'Divide and Conquer' pattern. We check the middle, and then solve the same problem on a smaller subarray (either left or right half).
Detailed Dry Run
Target: 9, Range: [0, 5]
mid = 2 (val 3). 3 < 9. Recurse right half [3, 5].mid = 4 (val 9). 9 == 9. Return 4.
Level III: Optimal (Iterative Binary Search)
Intuition
Iterative binary search is the industry standard. It achieves the same time but uses constant space by avoiding recursion. Key point: Always use mid = l + (r - l) / 2 to avoid integer overflow.
Detailed Dry Run
| Step | L | R | Mid | nums[Mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 3 | 3 < 9 → L = 3 |
| 2 | 3 | 5 | 4 | 9 | 9 == 9 → Return 4 |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.