Article written by Rishabh Dev Choudhary, under the guidance of Marcelo Lotif Araujo, a Senior Software Developer and an AI Engineer. Reviewed by Mrudang Vora, an Engineering Leader with 15+ years of experience.
Binary search can find any element in a sorted array of 1 billion items in at most 30 comparisons. Linear search could take up to 1 billion. That is the power of O(log n) and why binary search is one of the most tested algorithms in coding interviews. The prerequisite: the array must be sorted and support O(1) random access.
This article covers how binary search works with a step-by-step dry run, iterative and recursive implementations in Python, Java, and C++, complexity analysis, the mid-index overflow bug, and the interview patterns that separate strong candidates from average ones.
Binary search is a divide-and-conquer search algorithm that works on sorted arrays. It compares the target value to the middle element of the array, then discards half the search space based on whether the target is smaller or larger. This halving continues until the target is found or the search space is empty. Two prerequisites: the data must be sorted, and you must be able to access any element in O(1) time (arrays work; linked lists do not).
There are two key instances when you can use binary search:
The following steps are executed when running the binary search:
Dry run: Array [3, 7, 11, 14, 20, 28, 35, 42, 50, 61], Target = 28
| Step | low | high | mid | arr[mid] | Action |
| 1 | 0 | 9 | 4 | 20 | 20 < 28, so set low = mid + 1 = 5 |
| 2 | 5 | 9 | 7 | 42 | 42 > 28, so set high = mid – 1 = 6 |
| 3 | 5 | 6 | 5 | 28 | 28 == 28. Target found at index 5. |
The following are the steps of the binary search algorithm:
Iterative pseudocode (use mid = low + (high – low) / 2 to prevent overflow)
binarySearch(arr, target): low = 0, high = len(arr) - 1 while low <= high: mid = low + (high - low) / 2 // prevents integer overflow if arr[mid] == target: return mid else if arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1
Iterative – Python
def binary_search(arr, target): low, high = 0, len(arr) - 1 while low <= high: mid = low + (high - low) // 2 if arr[mid] == target: return mid elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1
Recursive – Python
def binary_search_rec(arr, target, low, high): if low > high: return -1 mid = low + (high - low) // 2 if arr[mid] == target: return mid elif arr[mid] < target: return binary_search_rec(arr, target, mid + 1, high) else: return binary_search_rec(arr, target, low, mid - 1)
Iterative – Java
static int binarySearch(int[] arr, int target) { int low = 0, high = arr.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; else if (arr[mid] < target) low = mid + 1; else high = mid - 1; } return -1; }
Iterative – C++
int binarySearch(vector<int>& arr, int target) { int low = 0, high = arr.size() - 1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; else if (arr[mid] < target) low = mid + 1; else high = mid - 1; } return -1; }
| Aspect | Iterative | Recursive |
| Time complexity | O(log n) | O(log n) |
| Space complexity | O(1): no call stack | O(log n): call stack depth equals recursion depth |
| Code length | Slightly longer | Slightly shorter and more readable |
| Risk of stack overflow | None | Possible on very large arrays with deep recursion |
| Preferred in interviews | Yes: avoids call stack overhead, simpler to trace on paper | No: use only when explicitly asked for the recursive variant |
| Case | Time Complexity | Space (Iterative) | Space (Recursive) | Why |
| Best case | O(1) | O(1) | O(log n) | Target is at the midpoint on the first comparison. |
| Average case | O(log n) | O(1) | O(log n) | Each comparison halves the search space: log2(n) steps maximum. |
| Worst case | O(log n) | O(1) | O(log n) | Target is at the last element checked or not present. Still only log2(n) comparisons. |
When low and high are both large integers, for example when they are both close to INT_MAX in a 32-bit system, the expression low + high overflows. In Java and C++ this wraps to a negative number, producing an invalid index. The form low + (high – low) / 2 is always safe because high minus low is always non-negative and smaller than either value alone. This bug was present in Java’s standard library binary search implementation until it was corrected in 2006. It is a documented FAANG interview question at Google and Meta.
| Aspect | Binary Search | Linear Search |
| Time complexity | O(log n) | O(n) |
| Prerequisite | Array must be sorted | No prerequisite |
| Best case | O(1) if target is at midpoint | O(1) if target is at index 0 |
| Worst case | O(log n) | O(n) |
| Data structure | Arrays (O(1) access required) | Arrays and linked lists |
| Best for | Large sorted datasets where multiple searches will be run | Small datasets, unsorted data, or single searches where sorting cost exceeds search cost |
Binary search is a recurring pattern across multiple interview problem categories. The key insight for advanced patterns: binary search applies to any search space with a monotonic condition, not just sorted arrays.
| Pattern | Description | Classic Problems |
| Basic binary search | Search for a target value in a sorted array | LeetCode 704: Binary Search |
| First/last occurrence | Modified binary search that continues after finding a match to find the boundary | LeetCode 34: Find First and Last Position of Element in Sorted Array |
| Search in rotated sorted array | Find which half is sorted, then determine which half contains the target | LeetCode 33: Search in Rotated Sorted Array |
| Find peak element | Binary search on a condition (peak means arr[mid] > arr[mid+1]) rather than a target value | LeetCode 162: Find Peak Element |
| Binary search on answer | Apply binary search to a range of possible answers, not an array. Search for the minimum/maximum value that satisfies a condition. | LeetCode 1011: Capacity to Ship, LeetCode 875: Koko Eating Bananas |
Binary search is O(log n), requires a sorted array, and is the most efficient general-purpose search algorithm. Understanding the mid overflow bug, the iterative vs recursive tradeoff, and the binary search on answer pattern separates candidates who have used binary search from those who truly understand it. For structured preparation, many candidates explore a FAANG interview preparation program to strengthen problem-solving and coding interview skills systematically.
The data structure must be sorted and must support O(1) random access. Arrays satisfy both. Linked lists do not: finding the middle element requires O(n) traversal, which eliminates the logarithmic advantage entirely.
Binary search requires O(1) access to the middle element. In a linked list, finding the middle element requires O(n) traversal. This makes the combined complexity O(n log n), which is worse than linear search at O(n). Use linear search on linked lists, or sort the list and convert to an array first.
Stability is a concept for sorting algorithms, not search algorithms. Binary search is deterministic: if the array has duplicate values it will find one occurrence but does not guarantee which one. To find the first or last occurrence of a value in an array with duplicates, use the first/last occurrence variant shown in the interview patterns table above.
Binary search is an algorithm applied to a sorted array. A binary search tree (BST) is a data structure where every node satisfies the BST property. Both achieve O(log n) search on average, but they operate on different data structures: binary search on a sorted array, BST traversal on a tree structure via pointer navigation.
Recommended Reads:
Time Zone:
100% Free — No credit card needed.
Time Zone:
Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.
Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.
Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.
Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.
Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.
End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.
Learn to build AI agents to automate your repetitive workflows
Upskill yourself with AI and Machine learning skills
Prepare for the toughest interviews with FAANG+ mentorship
Time Zone:
Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills
25,000+ Professionals Trained
₹23 LPA Average Hike 60% Average Hike
600+ MAANG+ Instructors
Webinar Slot Blocked
Register for our webinar
Learn about hiring processes, interview strategies. Find the best course for you.
ⓘ Used to send reminder for webinar
Time Zone: Asia/Kolkata
Time Zone: Asia/Kolkata
Hands-on AI/ML learning + interview prep to help you win
Explore your personalized path to AI/ML/Gen AI success
The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants
The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer
The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary
Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills
Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills
Webinar Slot Blocked
Time Zone: Asia/Kolkata
Hands-on AI/ML learning + interview prep to help you win
Time Zone: Asia/Kolkata
Hands-on AI/ML learning + interview prep to help you win
Explore your personalized path to AI/ML/Gen AI success
See you there!