Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Algorithms
Algorithmsmedium

Common binary search pitfalls — name one and how to avoid it.

Tags
#binary-search#bugs#overflow
Back to categoryPractice quiz

Answer

Common bugs are inconsistent bounds (infinite loop) and overflow when computing mid. Use `mid = left + (right - left) / 2` and be consistent with inclusive/exclusive ranges.

function binarySearch(arr: number[], target: number): number {
  let left = 0;
  let right = arr.length - 1;

  while (left <= right) {
    const mid = left + Math.floor((right - left) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) left = mid + 1;
    else right = mid - 1;
  }

  return -1;
}

Advanced answer

Deep dive

Binary search is all about invariants. Pick one boundary convention and stick to it.

A very safe choice is the half-open interval [l, r):

  • l starts at 0, r at n
  • loop while l < r
  • mid = l + (r-l)/2
  • if condition holds, move r = mid else l = mid + 1

Example: lower bound (first index with a[i] >= x)

function lowerBound(a: number[], x: number) {
  let l = 0, r = a.length
  while (l < r) {
    const mid = l + Math.floor((r - l) / 2)
    if (a[mid] >= x) r = mid
    else l = mid + 1
  }
  return l
}

Common pitfalls

  • Searching in an unsorted array / non-monotone predicate.
  • Duplicates: not deciding whether you want first/last occurrence.
  • Infinite loops due to `l = mid` / `r = mid` without progress.

Related questions

Algorithms
Binary search on answer (parametric search): when is it applicable?
#binary-search#parametric-search#monotonic
Algorithms
Explain Binary Search.
#search#binary-search#algorithm
Databases
SQL NULL: why is `col = NULL` not true and what should you use?
#sql
#null
#three-valued-logic