DSA AnimatorDSA animations
Binary Search LC #704 Easy Binary Search
Problem

Given an array of integers nums sorted in ascending order and an integer target, return the index of target if it exists in nums, otherwise return -1. The algorithm must run in O(log n) time.

Example 1
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums at index 4.
Example 2
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums, so return -1.
Constraints: 1 ≤ nums.length ≤ 10⁴  |  −10⁴ < nums[i], target < 10⁴  |  All integers in nums are unique and sorted ascending.
Sorted array · 20 elements

Click any number to search for it, or type one that isn't in the array.

comparisons: 0 a linear scan would need:
Variables
lo
hi
mid
nums[mid]
comparison
Step Logic
Press ▶ Play or Next Step to begin the animation.
Ready
0 / 0
Pick a target and press Play.
Algorithm
1
Init lo = 0, hi = nums.length − 1
2
While lo ≤ hi: mid = lo + (hi − lo) / 2
3
If nums[mid] == target → return mid
4
If nums[mid] < targetlo = mid + 1 (discard the left half)
5
Else → hi = mid − 1 (discard the right half)
6
Range empty (lo > hi) → return -1
Time
O(log n)
Space
O(1)
Why it's so fast

Every comparison throws away half of what's left, so the range shrinks 20 → 10 → 5 → 2 → 1. Even for 1,000,000 sorted numbers binary search needs at most 20 comparisons, while a linear scan may need a million. Use lo + (hi − lo) / 2 instead of (lo + hi) / 2 so the sum can't overflow for large indices.

Edge cases

Target smaller than every element, larger than every element, equal to the first or last element, and a single-element array. Try each one with the chips above: the loop always ends with either a match or an empty range.