15% off all plans & roadmaps Use code

See plans

Binary Search

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 nums are unique.
  • nums is 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Loop i from 0 to the last index.
  2. If nums[i] equals target, return i.
  3. 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

TimeO(n)
SpaceO(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 -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

  1. Loop i from 0 to the last index.
  2. If nums[i] equals target, return i.
  3. If nums[i] is greater than target, stop the loop, because no later value can match.
  4. 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

TimeO(n)
SpaceO(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 -1
On Sorted Array/List pattern infographic for Binary Search

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

  1. Set left = 0 and right = len(nums) - 1.
  2. Loop while left <= right, so a window of one element still gets checked.
  3. Compute mid = left + (right - left) / 2 using integer division.
  4. If nums[mid] equals target, return mid.
  5. If nums[mid] is less than target, set left = mid + 1.
  6. Otherwise set right = mid - 1.
  7. 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.

Stepleftrightmidnums[mid]ComparisonAction
104255 < 10left = 3
234377 < 10left = 4
344499 < 10left = 5
454nonenoneleft > rightexit 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

TimeO(log n)
SpaceO(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 -1

Common mistakes

  • Writing while left < right instead of while 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 = mid or right = mid instead of mid + 1 or mid - 1. Once mid has 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) / 2 in Java, C++ or C#. The sum can overflow a 32-bit int on large arrays and produce a negative index. Write left + (right - left) / 2.
  • Using / for mid in JavaScript without Math.floor. JavaScript division returns a fraction such as 2.5, and nums[2.5] is undefined, so the comparison silently fails. Wrap it in Math.floor.
  • Mixing a half-open window with a closed one, for example right = len(nums) together with right = mid - 1. Pick one convention and keep initial value, loop condition and updates consistent with it.
  • Returning mid from the wrong place or returning left at the end. For this problem a miss must return -1. Returning left is 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, sets right = -1, exits and returns -1.
  • Target smaller than every element, such as [1,3,5], target = 0: right keeps 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: left moves past the last index and the function returns -1.
  • Target at the first or last index, such as [1,3,5,7], target = 1 and target = 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, record mid as a candidate and set right = mid - 1 to keep looking left. When it is smaller, set left = 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 left and right, return -1 when left > 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

Practise it