Binary Search
An easy Binary Search problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Binary Search
- Sheets
- 3
- Core for
- 7 roles
- Platform
- LeetCode
The problem
Given a sorted array of integers and a target value, return the index where the target is found. If the target is not present, 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
- Why
- 9 exists in nums at index 4, so we return 4.
Example 2
- Input
- nums = [-1,0,3,5,9,12], target = 2
- Output
- -1
- Why
- 2 does not exist in nums, so we return -1.
Constraints
- 1 <= nums.length <= 10^4
- -10^4 <= nums[i] <= 10^4
- nums is sorted in ascending order
- -10^4 <= target <= 10^4
How to think about it
Updated 2026-09-09Every probe against the middle item cuts the search domain strictly in half. Because the values are ordered, observing a value smaller than the target does not merely eliminate that single element; it rules out the entire left half of the current range at zero additional cost.
Approaches, worst first
Linear sweep
time O(n) · space O(1)
Walk from the first index toward the end, comparing each item to the target. It requires no assumptions about ordering, which is also why it wastes the sorted guarantee and checks candidates that could never match.
Classic binary searchWrite this one
time O(log n) · space O(1)
Maintain two inclusive pointers around the remaining search boundary. Inspect the middle value and contract either boundary inward past that index on each mismatch until the target appears or the pointers cross.
Where people lose marks · 3
- Computing mid as (low + high) / 2 triggers signed 32-bit integer overflow in languages with fixed-width integers when the boundary indices grow large; use low + (high - low) / 2.
- Updating boundaries with low = mid or high = mid instead of stepping past with mid + 1 or mid - 1 causes an infinite loop whenever high - low equals one.
- Loop condition low < high instead of low <= high terminates prematurely before evaluating a single remaining candidate when low equals high.
Full solution
Classic binary search: contract low/high past the middle index on each mismatch. O(log n) time, O(1) space, the only approach that meets the problem's stated time bound.
Python
def binary_search(nums: list[int], target: int) -> int:
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2 # avoids overflow vs (low + high) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
JavaScript
function binarySearch(nums, target) {
let low = 0;
let high = nums.length - 1;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
if (nums[mid] === target) return mid;
if (nums[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
The theory behind it
Binary Search — the ground this problem stands on. All Binary Search problems
What Binary Search is
Binary search is the guessing strategy used when searching a thick telephone directory or guessing a secret number between one and a hundred. Rather than inspecting names one by one from the first page, the search opens straight to the middle page. If the target precedes that middle entry, the entire back half is discarded; if it follows, the front half is eliminated. Repeating this halved split finds the item with remarkable speed.
When to reach for it
Reach for binary search when queries target sorted collections, rotated sorted arrays, or monotonic answer spaces. Strong hints include logarithmic time constraints like O(log n) or search ranges exceeding one billion where stepping one value at a time times out. It also applies when validating whether a guessed solution is possible via a monotonic boolean check, known as binary search on answer.
How the pattern works
Define the search territory with two inclusive pointers, low and high. Compute the midpoint using low plus half the difference to high, avoiding integer overflow. Formulate an exact boolean condition that divides the range into true and false halves. Decide whether the boundary condition includes the midpoint or shifts strictly past it. The loop invariant states that the sought target, if it exists, remains trapped inside the interval throughout every iteration.
What each operation costs
| Operation | Time |
|---|---|
| find target in sorted array | O(log n) |
| find boundary in monotonic range | O(log n) |
What usually goes wrong with Binary Search
- Triggering integer overflow by computing middle using low plus high divided by two instead of low plus half of high minus low in fixed-width numeric types.
- Creating an infinite loop when the interval shrinks to two elements by setting low equal to mid when mid was rounded down.
- Mismatched loop condition and bounds updates, such as pairing low less than or equal to high with non-advancing pointer assignments that never terminate.
Which roles need this problem
Binary Search is a core topic for these 7 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 17 more roles, including Full-Stack Developer, Data Engineer, Android Developer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Binary Search problems
Problem set and role mapping as of .