Each step halves the remaining work.Classic sign: dividing the problem space in two.
Example
// JavaScriptfunctionbinarySearch(arr, target){let lo =0, hi = arr.length-1;while(lo <= hi){const mid = lo +Math.floor((hi - lo)/2);if(arr[mid]=== target)return mid;elseif(arr[mid]< target) lo = mid +1;else hi = mid -1;}return-1;}
# Python
def binary_search(arr, target):
lo, hi =0,len(arr)-1while lo <= hi:
mid = lo +(hi - lo)// 2if arr[mid]== target:return mid
elif arr[mid]< target:
lo = mid +1else:
hi = mid -1return-1
Output
Time: O(log n) | Space: O(1)
Note Balanced BST operations are O(log n). Use mid = lo + (hi - lo) // 2 instead of (lo + hi) // 2 to prevent integer overflow. If you see 'sorted array' in a problem, think binary search immediately.
lo =0, hi = length -1while lo <= hi:
mid = lo +(hi - lo)// 2
compare and adjust lo or hi
Example
// JavaScriptfunctionbinarySearch(arr, target){let lo =0, hi = arr.length-1;while(lo <= hi){const mid = lo +Math.floor((hi - lo)/2);if(arr[mid]=== target)return mid;if(arr[mid]< target) lo = mid +1;else hi = mid -1;}return-1;// not found}
# Python
def binary_search(arr, target):
lo, hi =0,len(arr)-1while lo <= hi:
mid = lo +(hi - lo)// 2if arr[mid]== target:return mid
elif arr[mid]< target:
lo = mid +1else:
hi = mid -1return-1
Output
binary_search([1,3,5,7,9,11], 7) → 3
Note Time O(log n), Space O(1). Off-by-one errors are the #1 bug - practice until the template is muscle memory. Use lo <= hi when searching for exact match. Use lo < hi when narrowing to a single candidate. Always test with 0, 1, and 2 element arrays.
Note which shows the full path of a command. whereis also shows man pages and source locations. In scripts, prefer command -v over which because it is POSIX-compliant and handles aliases/builtins correctly.
Frequently asked questions
How does Interview Prep handle binary search?
This task is covered in 2 stacks on this page: Interview Prep, Bash & Linux. The "O(log n) - Logarithmic Time" snippet in Interview Prep uses `Each step halves the remaining work. Classic sign: dividing the problem space in two.`.
Which code does the Interview Prep example use?
The "O(log n) - Logarithmic Time" snippet uses `Each step halves the remaining work. Classic sign: dividing the problem space in two.`, from the Big-O Notation section of the Interview Prep cheat sheet.
Which stacks cover "binary search" on this page?
Interview Prep, Bash & Linux. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "O(log n) - Logarithmic Time": Balanced BST operations are O(log n). Use mid = lo + (hi - lo) // 2 instead of (lo + hi) // 2 to prevent integer overflow. If you see 'sorted array' in a problem, think binary search immediately.