Binary Search Explained: Python, Java, and Interview Patterns

Last updated by Abhinav Rawat on May 29, 2026 at 12:44 PM

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.

| Reading Time: 3 minutes

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.

Key Takeaways

  • Binary search is O(log n): searching 1 billion elements takes at most 30 comparisons.
  • Two prerequisites: sorted data and O(1) random access. Neither is optional.
  • Always use mid = low + (high – low) / 2 to prevent integer overflow at large index values.
  • Use the iterative version in interviews: same O(log n) time, O(1) space instead of O(log n) call stack.
  • Binary search on the answer is the most important advanced pattern: apply binary search to a range of possible answers, not just array indices.

What Is Binary Search?

What is binary search?

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).

When can you use binary search?

There are two key instances when you can use binary search:

  • The data structure is sorted or monotonic: any sequence where you can say ‘everything to the left satisfies condition X, everything to the right does not’ qualifies.
  • You can access any element in O(1) time: binary search requires jumping to the middle, which is instant in an array but O(n) in a linked list, eliminating the speedup.
Important generalisation: Binary search is not just for sorted arrays. Any problem where the search space has a monotonic condition can be solved with binary search. This is the foundation of the ‘binary search on answer’ pattern, which is one of the most commonly tested advanced interview patterns.

How Binary Search Works

How does binary search work step by step?

The following steps are executed when running the binary search:

  1. Set a low pointer to index 0 and a high pointer to the last index.
  2. Find the mid index: mid = low + (high – low) / 2.
  3. Compare arr[mid] to the target. If equal, return mid. If target is less, set high = mid – 1. If target is greater, set low = mid + 1.
  4. Repeat until low is greater than high (target not found) or target is found.

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.
Loop termination: The loop runs while low <= high, not low < high. Missing the equals sign is the single most common off-by-one error in binary search implementations and is explicitly tested in FAANG interviews. If you write low < high, you will miss the case where the target is the only remaining element.

Binary Search Algorithm Steps

What are the steps of the binary search algorithm?

The following are the steps of the binary search algorithm:

  1. Initialise low = 0 and high = length – 1.
  2. While low <= high: calculate mid = low + (high – low) / 2.
  3. If arr[mid] equals target: return mid.
  4. If arr[mid] is less than target: set low = mid + 1.
  5. If arr[mid] is greater than target: set high = mid – 1.
  6. If the loop ends without finding target: return -1.

Binary Search Pseudocode

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

Binary Search Code

How do you implement binary search in Python?

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)

How do you implement binary search in Java?

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;
}

How do you implement binary search in C++?

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;
}

Iterative vs Recursive Binary Search

What is the difference between iterative and recursive binary search?

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

Binary Search Time and Space Complexity

What is the time complexity of binary search?

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.
Why O(log n) not O(log2 n): In Big O notation the base of the logarithm is dropped because it is a constant factor. Binary search always halves the search space so log base 2 is implied, but the formal notation writes it as O(log n) regardless of base.

The Mid-Index Overflow Bug

Why should you write mid = low + (high – low) / 2 instead of mid = (low + high) / 2?

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.

💡 Pro Tip: Always write mid = low + (high – low) / 2 in any interview binary search implementation. Examiners at senior levels will notice the difference.

Binary Search vs Linear Search

How does binary search compare to linear search?

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 Interview Patterns

In which interview problem patterns does binary search appear?

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 on answer is the most underrated pattern: Most candidates learn binary search as ‘search for a value in a sorted array.’ The advanced pattern is binary search on the answer: applying the same halving logic to a range of possible answers rather than an array index. If you can define a monotonic condition on the answer space (for example, ‘is it possible to complete in X days?’), you can binary search on it. This pattern appears in Google, Meta, and Amazon hard-level problems and separates strong candidates from average ones.

Conclusion

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.

FAQs: Binary Search

Q1. What is the prerequisite for binary search?

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.

Q2. Why does binary search not work on linked lists?

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.

Q3. Is binary search stable?

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.

Q4. What is the difference between binary search and a binary search tree?

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:

Last updated on: May 29, 2026
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

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.

Select a course based on your goals

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

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

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

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

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

Transform Your Tech Career with AI Excellence

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

Loading_icon
Loading...
*Invalid Phone Number
By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Registration completed!

See you there!

Webinar on Friday, 18th April | 6 PM
Webinar details have been sent to your email
Mornings, 8-10 AM
Our Program Advisor will call you at this time