Skip to content
Veltoryx Technologies
FreeProblem 35● EasyLeetCode #704 ↗5 min readUpdated 30 October 2026

Binary Search

Find the index of a target value in a sorted ascending array in O(log n) time by halving the search range each step.

01The problem

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

InputOutputWhy
nums = [-1, 0, 3, 5, 9, 12], target = 949 exists at index 4
nums = [-1, 0, 3, 5, 9, 12], target = 2-12 does not exist in nums
nums = [5], target = 50Single element match
nums = [5], target = -5-1Single element miss

Constraints: 1 to 10,000 elements, sorted ascending with distinct integers.

02How to spot it

  • The input array is sorted in ascending order.
  • The runtime constraint explicitly demands O(log n) time.
  • Comparing against the middle element allows half of the remaining array to be discarded immediately.

So: classic binary search on a closed range [lo, hi].

03Pseudocode

text
lo = 0 ; hi = n - 1
while lo <= hi:
  mid = lo + (hi - lo) / 2
  if a[mid] == target: return mid
  if a[mid] < target: lo = mid + 1
  else: hi = mid - 1
return -1
  1. Look at the middle element mid.
  2. Target is bigger? Discard the left half: lo = mid + 1.
  3. Target is smaller? Discard the right half: hi = mid - 1. If equal, return mid.

04Watch it work

Visualizer · step through the algorithmnums = [-1,0,3,5,9,12], target = 9
-10
01
32
53
94
125
lohi

Start search for target 9 across full range [0 .. 5].

Pseudocode

  1. lo = 0 ; hi = n - 1
  2. while lo <= hi:
  3. mid = lo + (hi - lo) / 2
  4. if a[mid] == target: return mid
  5. if a[mid] < target: lo = mid + 1
  6. else: hi = mid - 1
  7. return -1

Variables

lo
0
hi
5
target
9
step 1 / 5

05Step-by-step dry run

  1. 1
    -10
    01
    32
    53
    94
    125
    lohi

    Start search for target 9 across full range [0 .. 5].

    lo = 0hi = 5target = 9

  2. 2
    -10
    01
    32
    53
    94
    125
    lomidhi

    Calculate middle index: mid = 2 (value = 3).

    lo = 0hi = 5mid = 2value = 3target = 9

  3. 3
    -10
    01
    32
    53
    94
    125
    lohi

    a[2] (3) < target (9). Target must be in right half: set lo = 3.

    lo = 3hi = 5target = 9

  4. 4
    -10
    01
    32
    53
    94
    125
    lomidhi

    Calculate middle index: mid = 4 (value = 9).

    lo = 3hi = 5mid = 4value = 9target = 9

  5. 5
    -10
    01
    32
    53
    94
    125
    lomidhi

    a[4] equals target 9! Found match at index 4.

    mid = 4result = 4

06Java solution

BinarySearch.java
public class BinarySearch {
    public static int search(int[] nums, int target) {
        int lo = 0, hi = nums.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2; // prevent integer overflow
            if (nums[mid] == target) return mid;
            if (nums[mid] < target) lo = mid + 1; // target is to the right
            else hi = mid - 1; // target is to the left
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(search(new int[]{-1, 0, 3, 5, 9, 12}, 9));
        System.out.println(search(new int[]{-1, 0, 3, 5, 9, 12}, 2));
        System.out.println(search(new int[]{5}, 5));
        System.out.println(search(new int[]{5}, -5));
    }
}
Expected output
4
-1
0
-1

Tricky lines, decoded

  • lo + (hi - lo) / 2: Prevents 32-bit integer overflow. Writing (lo + hi) / 2 can exceed Integer.MAX_VALUE when both bounds are large.
  • while (lo <= hi): Uses <= because a range containing exactly one element (lo == hi) must still be inspected.

07Why it works

Because nums is sorted in ascending order, every element to the left of mid is smaller than or equal to nums[mid], and every element to the right is greater than or equal to nums[mid]. Comparing target to nums[mid] determines with certainty which half cannot hold target. Discarding that half leaves target (if present) strictly inside [lo, hi]. The candidate range halves on every iteration, terminating in at most log₂ n steps.

Invariant: If target exists in nums, its index lies within the closed interval [lo, hi].

08Time and space

  • Time: O(log n). An array of 10,000 elements requires at most 14 comparisons.
  • Space: O(1). Only three integer variables (lo, mid, hi) are tracked.

09Edge cases

InputOutputWhy it matters
[5], target = 50Single element, found
[5], target = -5-1Single element, absent
[1, 3], target = 31Target is at the very end
[1, 3], target = 10Target is at the very beginning
[-1, 0, 3, 5], target = 2-1Target belongs between two adjacent values

10Common mistakes

  • Integer overflow with (lo + hi) / 2. When lo + hi exceeds 2³¹ − 1, the sum overflows to a negative number. Always write lo + (hi - lo) / 2.
  • Using while (lo < hi) with hi = mid - 1. This loop terminates prematurely when only one element remains, skipping the check for single-element arrays or the boundary element.
  • Writing lo = mid or hi = mid. In the exact-match template with integer division rounding down, lo = mid when hi = lo + 1 causes an infinite loop. Always use mid + 1 and mid - 1.

11Other approaches

ApproachTimeSpaceUse when
Linear scanO(n)O(1)Unsorted arrays only
Binary searchO(log n)O(1)Default interview solution
Arrays.binarySearchO(log n)O(1)Production code; returns negative on miss
Recursive searchO(log n)O(log n)Recursion demonstration, uses stack memory

12In the interview

  • Duplicates present? Classic binary search finds an arbitrary matching copy. Use lower bound or upper bound searches (Problem 39) to find the first or last occurrence.
  • Array of unknown or infinite size? Start with hi = 1, and repeatedly double hi *= 2 until nums[hi] >= target. Then binary search in [hi / 2, hi] in O(log n) time.

13Check your understanding

Quiz · 2 questions

0 of 2 answered

  1. 1. Why is lo + (hi - lo) / 2 preferred over (lo + hi) / 2 in binary search?

  2. 2. What happens in classic binary search if you write while (lo < hi) instead of while (lo <= hi)?

14Solve it yourself

Try it on LeetCode #704.