15% off all plans & roadmaps Use code
See plansBinary Search
- LeetCode 704
- Easy
- Binary Search Patterns
- On Sorted Array/List
Updated
TL;DR: Find a target in a sorted array of unique integers and return its index, or -1. Compare the target with the middle element and discard the half that cannot hold it, which gives O(log n) time.
Problem
You are given an integer array nums sorted in ascending order and an integer target. Write a function that searches for target in nums. If target is present, return its index. Otherwise, return -1.
Your algorithm must run in O(log n) time.
Example 1
Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 is in nums at index 4.
Example 2
Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 is not in nums, so the answer is -1.
Constraints
1 <= nums.length <= 10^4-10^4 < nums[i], target < 10^4- All integers in
numsare unique. numsis sorted in ascending order.
Constraints that matter
- The statement demands O(log n) time, so a plain scan of the array is not an accepted answer even though n is only 10^4 and it would pass the tests.
- The array is sorted ascending, and that is the whole reason you can throw away half of the remaining range after one comparison.
- All values are unique, so a match is the only match. You can return the first index you hit and never need to worry about which duplicate to report.
- n is at most 10^4, so left + right is at most about 2 * 10^4 and cannot overflow a 32-bit int here. Writing left + (right - left) / 2 anyway is a habit that protects you on larger inputs.
- The array has at least one element, but the target can still be smaller than the first value or larger than the last, so your loop must handle running off either end.
Hints
Hint 1
This is binary search on a sorted array.
Hint 2
Walk through the array from index 0 and compare every element with the target.
Solution
Intuition
This is binary search on a sorted array. The clue is the word sorted combined with a request for O(log n). Whenever a problem hands you ordered data and asks for a logarithmic bound, one comparison must be able to rule out a large chunk of the input.
Picture a sorted phone book where you open to the middle page, see whether the name you want comes before or after it, and tear off the half that cannot contain it. The middle comparison is the tear, and the remaining pages are the window [left, right] that still might hold the name.
Look at what a single comparison tells you. Pick any index mid. If nums[mid] is smaller than the target, then everything at or left of mid is also smaller, because the array only grows to the right. So the target, if it exists, lives strictly to the right. If nums[mid] is larger, the mirror argument discards mid and everything to its right.
Each step therefore cuts the live range roughly in half. A range of 10^4 elements shrinks to 5000, 2500, 1250 and so on. After about 14 steps only one candidate is left, so you do at most about 14 comparisons instead of 10^4.
The method works because of an invariant: if the target is in the array, it is inside the window [left, right]. The window starts as the whole array, and every move keeps the invariant true. An empty window proves the target is absent. Keep that in mind, because every bug on this problem is a way of breaking it.
Worked example
Input: nums = [1, 3, 5, 7, 9], target = 10 Output: -1 Explanation: Every value in the array is smaller than 10, so 10 cannot be present. The search ends with no match and the function returns -1.
Approach 1: Linear scan
Walk through the array from index 0 and compare every element with the target. Return the index of the first match. If the loop ends, return -1.
This is the first thing a beginner writes. It is correct, but it ignores that the array is sorted, so it breaks the O(log n) requirement.
Steps
- Loop
ifrom 0 to the last index. - If
nums[i]equalstarget, returni. - After the loop ends, return -1.
Dry run
On nums = [1, 3, 5, 7, 9], target = 10:
- i = 0: 1 is not 10.
- i = 1: 3 is not 10.
- i = 2: 5 is not 10.
- i = 3: 7 is not 10.
- i = 4: 9 is not 10.
The loop finishes with no match and the function returns -1. That cost 5 comparisons for 5 elements.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the length of nums. The loop body runs once per element and does one comparison, so a miss costs exactly n comparisons. You store only the loop index, so extra space is constant.
PythonTested in our runner
from typing import List, Optional
class Solution:
def search(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if nums[i] == target:
return i
return -1JavaTested in our runner
import java.util.*;
class Solution {
public int search(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
return i;
}
}
return -1;
}
}C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
int search(vector<int>& nums, int target) {
for (int i = 0; i < (int)nums.size(); i++) {
if (nums[i] == target) {
return i;
}
}
return -1;
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
if (nums[i] === target) {
return i;
}
}
return -1;
};GoTested in our runner
func search(nums []int, target int) int {
for i := 0; i < len(nums); i++ {
if nums[i] == target {
return i
}
}
return -1
}C#Tested in our runner
public class Solution {
public int search(int[] nums, int target) {
for (int i = 0; i < nums.Length; i++) {
if (nums[i] == target) {
return i;
}
}
return -1;
}
}Approach 2: Linear scan with early exit
What's slow: the plain scan keeps looking even after it has passed the place where the target would have to be. In a sorted array, the first value larger than the target proves the target is missing, since everything after it is larger still.
The insight that fixes it: use the order to stop early. This is the first step toward trusting the sort, but it is still linear in the worst case. A target near the end, or larger than every element, forces a full pass.
Steps
- Loop
ifrom 0 to the last index. - If
nums[i]equalstarget, returni. - If
nums[i]is greater thantarget, stop the loop, because no later value can match. - After the loop, return -1.
Dry run
On nums = [1, 3, 5, 7, 9], target = 10:
- i = 0: 1 is less than 10, continue.
- i = 1: 3 is less than 10, continue.
- i = 2: 5 is less than 10, continue.
- i = 3: 7 is less than 10, continue.
- i = 4: 9 is less than 10, continue.
No value ever exceeds 10, so the early exit never fires and the function returns -1. This example is the worst case, which is exactly why the trick does not change the bound.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the array length. The early exit helps only when the target is small or absent in the middle of the range. When the target is larger than every element, the loop still visits all n positions. Only the index is stored, so space is constant.
PythonTested in our runner
from typing import List, Optional
class Solution:
def search(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if nums[i] == target:
return i
if nums[i] > target:
break # sorted, so nothing later can match
return -1JavaTested in our runner
import java.util.*;
class Solution {
public int search(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
return i;
}
if (nums[i] > target) {
break; // sorted, so nothing later can match
}
}
return -1;
}
}C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
int search(vector<int>& nums, int target) {
for (int i = 0; i < (int)nums.size(); i++) {
if (nums[i] == target) {
return i;
}
if (nums[i] > target) {
break; // sorted, so nothing later can match
}
}
return -1;
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
if (nums[i] === target) {
return i;
}
if (nums[i] > target) {
break; // sorted, so nothing later can match
}
}
return -1;
};GoTested in our runner
func search(nums []int, target int) int {
for i := 0; i < len(nums); i++ {
if nums[i] == target {
return i
}
if nums[i] > target {
break // sorted, so nothing later can match
}
}
return -1
}C#Tested in our runner
public class Solution {
public int search(int[] nums, int target) {
for (int i = 0; i < nums.Length; i++) {
if (nums[i] == target) {
return i;
}
if (nums[i] > target) {
break; // sorted, so nothing later can match
}
}
return -1;
}
}
Solution pattern
On Sorted Array/List
Part of Binary Search Patterns
Approach 3: Iterative binary searchOptimalOn Sorted Array/List
What's slow: both scans examine elements one at a time, and each comparison removes only one candidate. With 10^4 elements that is up to 10^4 comparisons.
The insight that fixes it: compare against the middle element instead. One comparison with nums[mid] removes mid and the whole half on the wrong side. Keep a closed window [left, right] that is guaranteed to hold the target if it exists, and shrink it until it is empty or the target is found.
Why it is correct. The window [left, right] always contains the target if it exists anywhere in the array. Comparing with nums[mid] only discards indices that are provably on the wrong side, because the array is sorted and the values are unique. Since the window shrinks until it is empty, an empty window means the target was never in the array, so returning -1 is correct.
Steps
- Set
left = 0andright = len(nums) - 1. - Loop while
left <= right, so a window of one element still gets checked. - Compute
mid = left + (right - left) / 2using integer division. - If
nums[mid]equalstarget, returnmid. - If
nums[mid]is less thantarget, setleft = mid + 1. - Otherwise set
right = mid - 1. - When the loop exits, the window is empty, so return -1.
Dry run
Trace on nums = [1, 3, 5, 7, 9], target = 10. The table shows state at the start of each pass, then the decision.
| Step | left | right | mid | nums[mid] | Comparison | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 4 | 2 | 5 | 5 < 10 | left = 3 |
| 2 | 3 | 4 | 3 | 7 | 7 < 10 | left = 4 |
| 3 | 4 | 4 | 4 | 9 | 9 < 10 | left = 5 |
| 4 | 5 | 4 | none | none | left > right | exit loop |
The window is empty after step 3, so the function returns -1. It used 3 comparisons instead of 5. On the page's other example, [-1,0,3,5,9,12] with target 9, mid is 2 (value 3, go right), then mid is 4 (value 9), and the answer is 4.
Complexity
| Time | O(log n) |
|---|---|
| Space | O(1) |
Here n is the array length. Each pass either returns or shrinks the window from size w to at most floor(w / 2), because we drop mid and one full side. The size can be halved at most about log2(n) + 1 times before it reaches zero, so the loop runs O(log n) times with O(1) work each. We keep only left, right and mid, so space is constant.
PythonTested in our runner
from typing import List, Optional
class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1 # target can only be on the right
else:
right = mid - 1 # target can only be on the left
return -1JavaTested in our runner
import java.util.*;
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] < target) {
left = mid + 1; // target can only be on the right
} else {
right = mid - 1; // target can only be on the left
}
}
return -1;
}
}C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = (int)nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] < target) {
left = mid + 1; // target can only be on the right
} else {
right = mid - 1; // target can only be on the left
}
}
return -1;
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (nums[mid] === target) {
return mid;
}
if (nums[mid] < target) {
left = mid + 1; // target can only be on the right
} else {
right = mid - 1; // target can only be on the left
}
}
return -1;
};GoTested in our runner
func search(nums []int, target int) int {
left, right := 0, len(nums)-1
for left <= right {
mid := left + (right-left)/2
if nums[mid] == target {
return mid
}
if nums[mid] < target {
left = mid + 1 // target can only be on the right
} else {
right = mid - 1 // target can only be on the left
}
}
return -1
}C#Tested in our runner
public class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.Length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] < target) {
left = mid + 1; // target can only be on the right
} else {
right = mid - 1; // target can only be on the left
}
}
return -1;
}
}Common mistakes
- Writing
while left < rightinstead ofwhile left <= right. When the window shrinks to one element, the loop exits without checking it, so a target sitting in that last slot is missed. Use<=with a closed window. - Setting
left = midorright = midinstead ofmid + 1ormid - 1. Oncemidhas been checked and rejected, it must leave the window. Otherwise a two-element window can stay the same forever and the loop never ends. - Computing
mid = (left + right) / 2in Java, C++ or C#. The sum can overflow a 32-bit int on large arrays and produce a negative index. Writeleft + (right - left) / 2. - Using
/formidin JavaScript withoutMath.floor. JavaScript division returns a fraction such as 2.5, andnums[2.5]is undefined, so the comparison silently fails. Wrap it inMath.floor. - Mixing a half-open window with a closed one, for example
right = len(nums)together withright = mid - 1. Pick one convention and keep initial value, loop condition and updates consistent with it. - Returning
midfrom the wrong place or returningleftat the end. For this problem a miss must return -1. Returningleftis the Search Insert Position answer, not this one.
Edge cases
nums = [5], target = 5: one element that matches. The window has size one, so the loop must run once and return 0.nums = [5], target = 2: one element that does not match. The loop runs once, setsright = -1, exits and returns -1.- Target smaller than every element, such as
[1,3,5], target = 0:rightkeeps moving left until it reaches -1, and the function returns -1 without an out-of-range read. - Target larger than every element, such as
[1,3,5], target = 9:leftmoves past the last index and the function returns -1. - Target at the first or last index, such as
[1,3,5,7], target = 1andtarget = 7: both must be found, which tests that neither end is dropped by an off-by-one. - Negative values, such as
[-9,-3,0,4], target = -3: the sort order and midpoint maths work the same, and the answer is 1.
Follow-ups interviewers ask
- What if the array contains duplicates and you must return the first index of the target?
- Do not return on a match. When
nums[mid] >= target, recordmidas a candidate and setright = mid - 1to keep looking left. When it is smaller, setleft = mid + 1. The last recorded candidate, if its value equals the target, is the leftmost index. This is the lower-bound template, and it is still O(log n). - Can you write it recursively, and what does it cost?
- Yes. Define a helper taking
leftandright, return -1 whenleft > right, and recurse on the half that can hold the target. Time stays O(log n), but the call stack goes about log2(n) deep, so space is O(log n) instead of O(1). With n at most 10^4 the depth is around 14, which is safe, but the loop is cleaner. - What if the array is sorted but you do not know its length, or it is too large for memory?
- For unknown length, probe indices 1, 2, 4, 8 and so on until the value at the probe is at least the target or the access fails, then binary search inside that last range. That takes O(log p) where p is the position of the target. For data on disk, the same halving applies to file offsets, and you read only about log2(n) blocks, which is why indexes and sorted files use this idea.
Binary Search FAQ
What is the time complexity of Binary Search?
Binary search runs in O(log n) time, where n is the number of elements. Each loop pass removes the middle element and one whole side, so the window at least halves. At most about log2(n) + 1 passes happen before the window is empty. Space is O(1) for the iterative version.
Why use binary search for LeetCode 704?
The array is sorted, so one comparison with the middle value rules out half the remaining indices. A linear scan cannot use that fact and costs O(n). The problem statement requires O(log n), and halving the search window is the standard way to reach it.
Can Binary Search be solved in O(1) extra space?
Yes. The iterative version stores only left, right and mid, so extra space is constant. The recursive version uses O(log n) stack space, because each call handles one half and the depth is about log2(n).
Why do you write mid = left + (right - left) / 2 instead of (left + right) / 2?
Both give the same value mathematically. In Java, C++ and C#, left + right can exceed the 32-bit int limit on very large arrays and wrap to a negative number. The subtraction form never exceeds right, so it is always safe. Python integers do not overflow, but the habit costs nothing.
What is the difference between while left <= right and while left < right?
With left <= right and a closed window [left, right], you check a one-element window before stopping, and you move bounds with mid + 1 and mid - 1. With left < right you normally use a half-open or boundary-finding template, where right = mid is allowed. Mixing the two styles is the most common source of missed elements and infinite loops.
Is this page about binary search or about binary numbers?
It is about binary search, the algorithm that halves a sorted range to find a value. It has nothing to do with adding, subtracting, multiplying or dividing numbers written in base 2. The word binary here refers to splitting the search range into two halves.
Asked at
See which companies ask this — Pro
Related problems
- Search Insert Position · same technique: On Sorted Array/List
- Sqrt(x) · same technique: On Sorted Array/List
- Guess Number Higher or Lower · same technique: On Sorted Array/List
- First Bad Version · same technique: On Sorted Array/List
- Kth Missing Positive Number · same technique: On Sorted Array/List
- Koko Eating Bananas · next harder, same pattern
- Search in Rotated Sorted Array · same pattern: Binary Search Patterns
- Find Minimum in Rotated Sorted Array · same pattern: Binary Search Patterns
- Search a 2D Matrix · same pattern: Binary Search Patterns
- Find K Closest Elements · same pattern: Binary Search Patterns