Binary Search (Find Boundaries)

Use this to find the "first" or "last" occurrence in a sorted space with O(log N) time complexity.

Recognition

  • Search space is monotonic: once a predicate flips, it stays flipped.
  • You need the first/last valid boundary rather than an exact match only.

When not to use it

Do not force this pattern when the input is unordered and hashing is enough.

Avoid coding the template before naming the invariant you need to preserve.

Logic template

Python

def binary_search(nums, target, find_first):
    l, r = 0, len(nums) - 1
    ans = -1
    while l <= r:
        mid = l + (r - l) // 2
        if nums[mid] == target:
            ans = mid
            if find_first: r = mid - 1 # Nudge left
            else: l = mid + 1          # Nudge right
        elif nums[mid] < target:
            l = mid + 1
        else:
            r = mid - 1
    return ans

JavaScript

function binarySearch(nums, target, findFirst) {
  let l = 0, r = nums.length - 1;
  let ans = -1;
  while (l <= r) {
    let mid = Math.floor(l + (r - l) / 2);
    if (nums[mid] === target) {
      ans = mid;
      if (findFirst) r = mid - 1; // Nudge left
      else l = mid + 1;           // Nudge right
    } else if (nums[mid] < target) {
      l = mid + 1;
    } else {
      r = mid - 1;
    }
  }
  return ans;
}

Typically better than the obvious O(N^2) approach; verify with the template.

  • Name what stays true after every move.
  • Track the exact condition that lets you discard work safely.

Worked example

Recognition drill

Identify the reusable state and the rule that advances it.

  1. Restate the goal in one sentence.
  2. Name the moving parts and what they represent.
  3. Write the loop invariant before coding.
  4. Trace one failing case that breaks a naive approach.

Result: You can explain when to reach for the pattern and when to abandon it.

Common pitfalls

  • Off-by-one updates on loop bounds.
  • Updating state after comparing instead of before.
  • Confusing “solved once” with pattern mastery.

Related practice problems