Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Binary Search

Binary Search

EASY✓ CHIP-TIMEDLC #704 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Locate a target value inside a sorted array of distinct integers and report its index — or flag its absence with -1. The array's sorted order is the only lever available; scanning ignores it, searching exploits it.

A sorted array of distinct integers arrives along with a target value, and the drill is to report the index where that target lives.

Sorted and distinct means every value appears at most once and the array never needs re-checking for duplicates — each value maps to exactly one position.

When the target isn't present anywhere in the array, the answer is -1 instead of any real index.

  • array length can reach into the tens of thousands
  • values are distinct and arranged in ascending order
  • target may or may not appear in the array
  • absence is signaled by returning -1
EX 01
nums = [-9, -4, 0, 3, 8, 12, 19] · target = 3
→ 3
middle-ish hit
EX 02
nums = [-9, -4, 0, 3, 8, 12, 19] · target = -9
→ 0
left boundary
EX 03
nums = [-9, -4, 0, 3, 8, 12, 19] · target = 19
→ 6
right boundary

The hintstake only what you need

HINT 1 THE NUDGE

A linear scan works but throws away the one fact this array gives you for free: it's sorted. What does sorted order let you rule out with a single comparison?

HINT 2 THE STRUCTURE

Compare the target to the middle element. If they don't match, an entire half of the array can never contain the answer — discard it outright.

HINT 3 ONE STEP FROM THE ANSWER

Keep shrinking a [lo, hi] window: check mid, move lo past it if target is bigger, move hi before it if target is smaller, stop when they cross or you land on a hit.

Coach's boardthe pattern, step by step

THE HALVING HUNTPATTERN · BINARY SEARCHnums = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] · target = 17
1
3
5
7
9
11
13
15
17
19
STEP 1

Target 17. The window starts as the whole array, indices 0 through 9 — sorted order lets us skip half each step.

STEP 1 / 7 · ← → WORK TOO

The splitstwo paces, two languages

grind/binary-search.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        lo, hi = 0, len(nums) - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                lo = mid + 1
            else:
                hi = mid - 1
        return -1
TIME O(LOG N)SPACE O(1)PYTHON · RACE PACE · 12 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED