Problem
FAANG · LeetCode #704

Binary Search — three-stage drill

1The ProblemEasy

Binary Search

Find a target's index in a sorted array (or −1).

sorted — find the index of9-10013253941259 is at index 4return4
Examples
[-1,0,3,5,9,12], t=9→ 4t=2→ -1

constraintArray is sorted ascending; distinct values.

2The PatternTIME O(log n) · SPACE O(1)

Binary Search

Halve the search space each step — check the middle, keep the half that can hold the answer.

check the middle, discard the half that can't hold the target1031527394115136157left›right↑ mid
Problems using this pattern
3The SolutionRESULT → 4

Step through it

target = 9-1001325394125leftright↩ ANSWERresult =?
left = 0, right = 5. target = 9 — search the whole sorted array
Step 1 / 3
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent