Halve the search space each step. Maintain lo & hi boundaries — compute mid, compare nums[mid] to target, discard the half that cannot contain the answer. Repeat until found or lo > hi.
Each iteration halves the search window: n → n/2 → n/4 → … → 1. Takes at most ⌈log₂ n⌉ steps. Only lo, hi, mid variables — no auxiliary array needed.
// ── Classic Binary Search ───────────────────────────────────────── int lo = 0, hi = nums.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; // avoids (lo+hi) overflow if (nums[mid] == target) { return mid; // ✅ found } else if (nums[mid] < target) { lo = mid + 1; // ↗️ target in right half } else { hi = mid - 1; // ↙️ target in left half } } return -1; // not found // ── Leftmost occurrence ─────────────────────────────────────────── // if (nums[mid] == target) { result = mid; hi = mid - 1; } // keep searching left // ── Rightmost occurrence ────────────────────────────────────────── // if (nums[mid] == target) { result = mid; lo = mid + 1; } // keep searching right