DSA
Master Binary Search Patterns: 5 templates for Coding Interviews
Master 5 binary search patterns techniques used in Google, Amazon, and Meta interviews.

You've spent hours grinding LeetCode. You're lightning-fast at solving "Search Insert Position" and "First Bad Version." But then your interviewer at Google throws you a rotated array, or asks for the k-th smallest pair distance. Suddenly, your confidence evaporates. The question looks like binary search... but you don't know which template to use, or how to adapt it.
Sound familiar?
You're not alone. The real challenge isn't memorizing a vanilla binary search—it's recognizing the pattern variations hiding beneath the surface. The difference between brute force and FAANG-level mastery? It's pattern recognition, not problem memorization. Once you can spot and flexibly apply the 5 essential binary search sub-patterns, you'll unlock a toolkit that solves 15%+ of all elite coding interviews.
What You'll Learn
By the end of this guide, you'll master:
✅ The 5 binary search sub-patterns that power FAANG interviews
✅ Pattern recognition skills to identify and attack any binary search variant
✅ 26 curated practice problems with real company tags (Google, Amazon, Meta, Apple, etc.)
✅ When to use each pattern, with recognition triggers and mental models
✅ Common pitfalls (and how to avoid them) that trip up even experienced engineers
✅ A structured practice roadmap to take you from "I kind of get binary search" to interview-ready mastery
What is Binary Search Patterns?
Think of binary search patterns like a master key—not just unlocking a single door, but a whole building of algorithmic challenges. Classic binary search is just the front door. But what about when the hallway is rotated, the doors are hidden, or you need to find the first door that opens, not just any door? That's where the sub-patterns come in.
The core insight: Binary search isn't just about "find the target in a sorted array." It's about divide and conquer on a monotonic function or ordered structure—using the minimum amount of information to home in on your answer.
Why This Pattern Matters
- Optimization Superpower: Transforms O(n) or O(n²) brute force into sleek O(log n) solutions.
- Interview Favorite: Over 15% of FAANG interviews include a binary search pattern (often in disguise).
- Real-World Impact: Powers everything from database indices (Google) to ad targeting (Meta) and recommendation systems (Amazon).
- Versatile Foundation: Mastering these patterns unlocks advanced topics—range queries, search space reduction, and more.
Companies that frequently ask binary search patterns: Google, Amazon, Meta, Apple, Microsoft, Bloomberg, Facebook, Uber, Goldman Sachs, Oracle
The 5 Binary Search Patterns Sub-Patterns
Let's break down the five core binary search variations. Each offers a unique mental model, recognition triggers, and interview power moves.
1. Find First/Last Occurrence
What it is:
This pattern extends binary search to locate the first or last occurrence of a target in a sorted array (which may contain duplicates), or to identify the k closest elements to a value. It's about pinpointing the bounds of a value's presence.
Key insight:
Instead of stopping at the first match, keep searching toward the left (for first) or right (for last) until you can't go further. By tightening your search region around the boundary, you ensure you catch the earliest or latest instance—even with duplicates.
How it works:
- Perform binary search as usual.
- When you find the target, record the index.
- Instead of exiting, move your search window:
- For first occurrence, search the left half (right = mid - 1).
- For last occurrence, search the right half (left = mid + 1).
- Repeat until left > right; return the boundary index.
When to use:
- Finding start/end positions of a specific value in a sorted array.
- Counting occurrences of a target.
- Problems asking for closest elements to a value.
- Any "find the range" or "find all positions" prompt.
Recognition triggers:
- "Find first/last occurrence," "range of target," "number of times target appears"
- "Return indices" or "return the range"
- "K closest elements"
Essential Problems:
Medium:
- ⭐ Find First and Last Position of Element in Sorted Array - Facebook, Amazon, Uber, Google, Microsoft
Classic: Given a sorted array, return the indices of the first and last appearance of a target value. - Find K Closest Elements - Facebook, Microsoft, Google, Paypal
Find the k elements closest to a target in a sorted array.
💡 Pro Tip:
In interviews, always clarify if the array can contain duplicates. If so, ask if they want the exact position or just existence—this affects your stopping condition.
⚠️ Common Mistake:
Many candidates stop at the first match and return, missing the need to keep searching for the true boundary. Always continue searching after a match, updating your answer each time.
Example Code Pattern:
PYTHON
Time/Space Complexity:
O(log n) time, O(1) space.
2. Find Min/Max in Rotated Sorted Array
What it is:
This pattern solves problems where a sorted array has been rotated at some pivot unknown to you. Your task is to find the minimum (or maximum), or to search efficiently within this disrupted order.
Key insight:
In a rotated sorted array, at least one half (left or right) remains sorted at each step. By comparing midpoints to endpoints, you can determine which side is unsorted (and thus contains the min/max or the pivot), shrinking your search space logarthmically.
How it works:
- Use binary search as the backbone.
- At each step, compare
nums[mid]withnums[right]ornums[left]. - If
nums[mid] > nums[right], the minimum is in the right half. - If
nums[mid] < nums[right], the minimum is in the left half (including mid). - Adjust your pointers accordingly.
- For finding peaks (mountain arrays), use the mid's relation to its neighbors.
When to use:
- Rotated sorted arrays (e.g., "rotated at an unknown pivot")
- Searching for min/max or a specific target in such arrays
- Mountain/peak finding in arrays
Recognition triggers:
- "Rotated sorted array," "find minimum (or maximum)"
- "Array may contain duplicates"
- "Mountain array," "peak element," "pivot point"
Essential Problems:
Medium:
- ⭐ Find Minimum in Rotated Sorted Array - Facebook, Amazon, Bloomberg, Goldman Sachs, Microsoft
Find the smallest element in a rotated sorted array. - ⭐ Search in Rotated Sorted Array - Amazon, Facebook, Microsoft, LinkedIn, Oracle
Classic: Search for a target in a rotated sorted array in O(log n) time. - Search in Rotated Sorted Array II - Amazon
Handles potential duplicates—watch for extra condition! - ⭐ Find Peak Element - Facebook, Amazon, Google, Bloomberg, Quora
Find any peak (greater than neighbors) in O(log n) time. - Peak Index in a Mountain Array - Bloomberg, Yahoo
Hard:
- Find in Mountain Array - Apple, Bloomberg, Quora
Search for a target given a "mountain" (increasing then decreasing) array.
💡 Pro Tip:
For "peak" problems, remember that a peak is any element greater than its neighbors (not necessarily the global max). For rotated arrays with duplicates, add an extra check to skip duplicates smartly (may degrade to O(n) in worst-case).
⚠️ Common Mistake:
Many confuse which half is sorted and which is unsorted—leading to incorrect pointer movement. Always check which side is strictly sorted (nums[left] <= nums[mid] or nums[mid] <= nums[right]).
Example Code Pattern:
PYTHON
Time/Space Complexity:
O(log n) time (unless duplicates degrade to O(n)), O(1) space.
3. Median and Kth of Two Sorted Arrays
What it is:
This advanced pattern finds the median or k-th smallest element across two sorted arrays (or via pairwise operations). It's a staple in high-difficulty interview rounds.
Key insight:
Instead of merging arrays to find the k-th element (O(n)), use binary search on indices or value ranges to discard large sections at each step. For medians, partition the arrays so that the left side contains k elements, then compare border values to find the correct split.
How it works:
- For k-th smallest: Recursively (or iteratively) discard k//2 elements from one array at a time, shrinking the search space.
- For median: Use binary search on partition indices to balance the left and right halves of both arrays.
- For distance-based kth (e.g., pairwise distances): Binary search on possible distances, counting how many pairs are ≤ mid.
When to use:
- "Median of two sorted arrays"
- "Find the k-th smallest/largest element"
- "Pairwise k-th values," "smallest/largest distances"
Recognition triggers:
- Two (or more) sorted arrays, need to find "k-th" or "median"
- "Without merging," "in O(log n) time"
- "Pairwise distance," "partition"
Essential Problems:
Hard:
- ⭐ Median of Two Sorted Arrays - Amazon, Goldman Sachs, Facebook, Microsoft, Apple
Find the median of two sorted arrays in O(log(min(m, n))). - Find K-th Smallest Pair Distance - Google, Amazon
Binary search on possible distances, not indices!
💡 Pro Tip:
Always binary search over the shorter array for simpler logic and fewer edge cases. For k-th smallest, reduce k greedily by chopping off the smaller k//2 chunk at each step.
⚠️ Common Mistake:
Merging arrays or using brute force (O(n)) won't pass large test cases. Avoid off-by-one errors in partitioning—draw the arrays and mark partitions on paper in interviews.
Example Code Pattern:
PYTHON
Time/Space Complexity:
O(log(min(m, n))) time, O(1) space.
4. On Answer / Condition Function
What it is:
This pattern uses binary search on the potential answer space—not on the values in an array, but on the range of possible solutions. At each step, a condition function tells you if a candidate answer is feasible, letting you shrink the range.
Key insight:
If your answer space is monotonic (true/false as you increase or decrease a parameter), you can binary search for the minimum or maximum feasible answer. This is common in allocation, scheduling, or optimization problems.
How it works:
- Define a function
canAchieve(x)that returns True ifxis a valid solution. - Binary search over the range of possible answers (e.g., min to max value).
- At each mid, use the condition function to decide which half to keep.
- Loop until you find the minimal/maximal feasible value.
When to use:
- Problems asking for "minimum x such that..." or "maximum x such that..."
- Feasibility checks over a continuous or integer answer space
- Scheduling, allocation, or resource distribution tasks
Recognition triggers:
- "Find the minimum/maximum value that meets a condition"
- "Given k, distribute/allocate/ship within y days"
- "Can you achieve...?" with a testable condition
Essential Problems:
Medium:
- ⭐ Capacity To Ship Packages Within D Days - Amazon, Flipkart
Find the minimal ship capacity to deliver packages in D days. - ⭐ Koko Eating Bananas - Facebook
Find the minimal eating speed for Koko to finish in h hours. - Maximum Candies Allocated to K Children
- Minimum Limit of Balls in a Bag - Flipkart
- Minimized Maximum of Products Distributed to Any Store
- Minimum Number of Days to Make m Bouquets - Google
Hard:
- Split Array Largest Sum - Amazon, Google
Split array into m parts, minimize the largest sum. - Minimize Max Distance to Gas Station - Google
💡 Pro Tip:
Always analyze whether your feasible region is truly monotonic—this is crucial for the binary search to work. In interviews, clearly explain your condition function and walk through a sample input.
⚠️ Common Mistake:
Forgetting to set the correct lower/upper bounds for your answer space. Always check edge cases (e.g., min = 1 vs min = max(arr)) and include both ends in your loop.
Example Code Pattern:
PYTHON
Time/Space Complexity:
O(n log m), where m is the answer space (e.g., max(piles)).
5. On Sorted Array/List
What it is:
The classic—applies binary search directly to a sorted array or list to find a target, missing element, square root, or insertion position. The most fundamental and direct variant.
Key insight:
By repeatedly splitting the search space in half, you can locate a target or determine its correct position in O(log n) time. This is the "base template" upon which all other patterns build.
How it works:
- Initialize pointers
left = 0,right = len(arr) - 1. - While
left <= right, computemid = (left + right) // 2. - If arr[mid] == target, return mid.
- If arr[mid] < target, move left pointer up.
- If arr[mid] > target, move right pointer down.
- For variants: tweak stopping conditions and return values accordingly.
When to use:
- Searching for a value in a sorted array/list
- Finding missing numbers or specific positions
- "Is target present?" or "Where should target be inserted?"
Recognition triggers:
- "Given a sorted array/list"
- "Find a value," "find missing," "find insert position"
- Explicitly asks for O(log n) time
Essential Problems:
Easy:
- ⭐ Binary Search - Microsoft, Facebook, Amazon
The template every engineer must master! - Kth Missing Positive Number - Facebook, Amazon, Microsoft, Apple
- First Bad Version - Facebook
- Guess Number Higher or Lower - Apple
- Sqrt(x) - Microsoft, Bloomberg, Amazon, Uber, LinkedIn
Find integer square root using binary search on answer. - Search Insert Position - Apple, Amazon
Medium:
- ⭐ Search a 2D Matrix - Amazon, Facebook, Apple, Microsoft, Nvidia
Flatten 2D matrix logic into 1D binary search. - Single Element in a Sorted Array - Amazon, Facebook, Twitter
💡 Pro Tip:
Practice writing the vanilla binary search template from scratch in 1-2 minutes. Variants often flip the "while" condition or pointer moves—be ready to adapt.
⚠️ Common Mistake:
Off-by-one errors: while left < right vs while left <= right, or returning left vs mid. Always walk through your code with a 1/2/3 element array and draw pointer movement!
Example Code Pattern:
PYTHON
Time/Space Complexity:
O(log n) time, O(1) space.
How to Master Binary Search Patterns on Thita.ai
Ready to go from "I get it in theory" to "I'm FAANG ready"? Thita.ai turbocharges your learning with:
-
Pattern-Based Problem Sets:
Practice every binary search sub-pattern in curated order. Jump to the DSA Patterns Sheet -
AI Hints & Instant Feedback:
Get unstuck instantly with context-aware hints, solution explanations, and code reviews. Start coding now -
Real Interview Simulation:
Face AI-driven interviewers who ask follow-ups, test edge cases, and give you a real FAANG experience. Simulate an interview -
Track Your Progress:
Visualize your strengths, weaknesses, and time-to-mastery by sub-pattern. See your dashboard -
Technical Coaching:
Access an AI coach for custom drills, resume feedback, and behavioral prep. Meet your AI coach
Your Binary Search Patterns Learning Roadmap
2-3 Weeks to Interview Mastery
(Estimate: 60-90 minutes per day)
Week 1: Foundations
Day 1:
- Binary Search (Microsoft, Facebook, Amazon)
- Search Insert Position (Apple, Amazon)
Goal: Master the template, practice pointer movement on paper.
Day 2:
- Guess Number Higher or Lower (Apple)
- Sqrt(x) (Microsoft, Bloomberg, Amazon, Uber, LinkedIn)
Goal: Apply binary search to alternative answer spaces.
Day 3-4:
- First Bad Version (Facebook)
- Kth Missing Positive Number (Facebook, Amazon, Microsoft, Apple)
- Review all previous problems, write your own test cases.
Week 2: Intermediate
Day 5:
- Find First and Last Position of Element in Sorted Array ⭐ (Facebook, Amazon, Uber, Google, Microsoft)
- Find K Closest Elements (Facebook, Microsoft, Google, Paypal)
Focus: Find First/Last Occurrence subpattern.
Day 6:
- Find Minimum in Rotated Sorted Array ⭐ (Facebook, Amazon, Bloomberg, Goldman Sachs, Microsoft)
- Search in Rotated Sorted Array ⭐ (Amazon, Facebook, Microsoft, LinkedIn, Oracle)
Focus: Rotation and pivots.
Day 7-8:
- Find Peak Element ⭐ (Facebook, Amazon, Google, Bloomberg, Quora)
- Peak Index in a Mountain Array (Bloomberg, Yahoo)
- Search a 2D Matrix ⭐ (Amazon, Facebook, Apple, Microsoft, Nvidia)
Focus: Peaks & matrix flattening.
Day 9:
- Single Element in a Sorted Array (Amazon, Facebook, Twitter)
- Search in Rotated Sorted Array II (Amazon)
- Review all week 2 problems, write pseudocode for each.
Week 3: Mastery
Day 10-11:
- Median of Two Sorted Arrays ⭐ (Amazon, Goldman Sachs, Facebook, Microsoft, Apple)
- Find K-th Smallest Pair Distance (Google, Amazon)
- Find in Mountain Array (Apple, Bloomberg, Quora)
Focus: Advanced/Hard subpatterns.
Day 12:
- Capacity To Ship Packages Within D Days ⭐ (Amazon, Flipkart)
- Koko Eating Bananas ⭐ (Facebook)
- Split Array Largest Sum (Amazon, Google)
Focus: On Answer/Condition Function.
Day 13-14:
- Timed mixed sets: Choose 3-5 problems across subpatterns at random from above.
- Dashboard: Review stats, revisit any weak areas.
Estimated time: 60-90 minutes per day. Adapt as needed—quality > quantity!
Common Binary Search Patterns Pitfalls
⚠️ 1. Off-by-One Errors
Mistake: Mixing up while left < right vs while left <= right, or returning left vs mid.
Solution: Always run your code on 1-2 element arrays and draw pointer movement. For example:
PYTHON
PYTHON
⚠️ 2. Stopping Too Early in First/Last Occurrence
Mistake: Returning as soon as you find target, without checking boundaries.
Solution: Keep searching left/right after a match, updating your answer each time.
⚠️ 3. Mishandling Rotated Arrays
Mistake: Failing to correctly identify sorted vs unsorted halves, leading to incorrect pointer updates.
Solution: Always check if nums[left] <= nums[mid] before deciding direction.
⚠️ 4. Not Defining the Condition Function Clearly
Mistake: In On Answer/Condition Function, using a non-monotonic or buggy feasibility function.
Solution: Write a clear, testable helper like can_finish(x) and verify on small examples.
⚠️ 5. Failing to Handle Duplicates in Rotated Arrays
Mistake: Not accounting for duplicate values, leading to infinite loops.
Solution: Add code to skip duplicates when nums[mid] == nums[left] == nums[right], or accept O(n) fallback.
⚠️ 6. Not Using the Shorter Array in Median/Kth Problems
Mistake: Binary searching the longer array, leading to more edge cases and potential index errors.
Solution: Always search on the smaller array for less complexity.
⚠️ 7. Inefficient Brute Force for K-th, Closest, or Peak Problems
Mistake: Resorting to full array scans, sorting, or merging.
Solution: Remember that binary search is about exploiting order and monotonicity—use it even when it doesn't look like a classic sorted array!
Why Binary Search Patterns Beat Brute Force
Let's examine Find First and Last Position of Element in Sorted Array:
Brute Force Approach:
PYTHON
- Time Complexity: O(n)
- Space Complexity: O(1)
Optimized Binary Search Pattern:
PYTHON
- Time Complexity: O(log n)
- Space Complexity: O(1)
Key Insight:
Binary search leverages the sorted structure to halve the search space at every step. For large arrays (think millions of elements), O(log n) solutions are orders of magnitude faster and scale to production-level demands.
When does this matter most?
When n is large (interviewers often hint at this), or when you need to run the operation many times (real-world systems, batch jobs).
Beyond LeetCode: Real-World Applications
Binary search patterns power some of the most critical backend systems at top tech companies. Here are just a few:
-
Database Indexing (Google, Amazon RDS):
Binary search is the backbone of B-trees and database indices. When you run a search query, the system uses a variant of binary search to instantly locate records in massive datasets. -
Recommendation Engines (Meta, Netflix):
Finding the top k recommendations, or the closest matches, often uses binary search on pre-sorted user/item vectors for lightning-fast lookups. -
Load Balancing & Resource Allocation (AWS, Google Cloud):
Scheduling tasks to minimize maximum server load? Binary search on answer space (On Condition Function) is used to determine minimal capacity or optimal distribution. -
Sensor Data Processing (Tesla, Apple):
Detecting sudden changes (peaks) in sensor streams or finding event boundaries uses peak-finding and range-search patterns. -
Ad Targeting (Meta, Google Ads):
Matching users to the most relevant ad slots often involves searching sorted budget/priority arrays using binary search for sub-second response times.
Performance Benefits:
In all these scenarios, binary search cuts latency and cost by orders of magnitude—enabling real-time, scalable systems.
Conclusion: From Memorization to Mastery
By now, you’ve seen that binary search is not just a single trick—it’s a toolbox of patterns. Mastering these unlocks 15%+ of all FAANG interview questions, and gives you real-world engineering superpowers.
Next Steps:
- Start practicing today with the DSA Pattern Sheet
- Simulate interviews with AI-driven interviewers
- Track your mastery with the personalized dashboard
- Get expert coaching with the AI coach for advanced tips and behavioral prep
Remember: Don't just memorize code. Understand the patterns, flex your recognition muscles, and you'll be ready for anything—on LeetCode, in interviews, and in real-world engineering.