DSA Tracker

Problem

Pattern this teaches:Binary Search on Sorted Data

Easy

Binary Search

An easy Binary Search interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Binary Search
Sheets
3
Core for
7 roles

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 = [-4,1,6,8,10,14], target = 8
Output
3
Why
8 sits at index 3.

Example 2

Input
nums = [-4,1,6,8,10,14], target = 5
Output
-1
Why
5 is not in the array.

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-29

Every 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

  1. 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.

  2. 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 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 search(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;
}
Try it in the editor

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.

More Binary Search problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .