Skip to main content

Binary Search

Given a sorted array nums and an integer target Return the index of target if it exists, otherwise return -1 Must use O(log n) time complexity Example: nums = [-1,0,3,5,9,12], target = 9 => 4

Find a target in a sorted array. It's the most fundamental divide-and-conquer algorithm, and getting the boundary conditions exactly right is trickier than it looks. Interviewers use it as a baseline—if you fumble binary search, they'll wonder about everything else.

Examples

You write

search(nums: List[int], target: int)

  1. Example 1

    Input
    nums = [-1,0,3,5,9,12], target = 9
    returns
    4
  2. Example 2

    Input
    nums = [-1,0,3,5,9,12], target = 2
    returns
    -1

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Binary Search

I reach for it when

  • The input is sorted, or sorted and then rotated.
  • You want a boundary: the first or last place something is true.

Say this before you type. Say the yes-or-no question, and which side each answer throws away.

All 19 Binary Search problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Find Target in Sorted Arrayeasy
2Part 2

Each locked part opens in the editor once the part before it passes.