Binary search is deceptively simple. The basic algorithm—divide the search space in half—takes five minutes to understand. But FAANG interviewers don't ask basic binary search. They ask variations that twist the concept, requiring deep understanding of how binary search actually works. Engineers who've only done textbook binary search often fail these questions, even though they're fundamentally about the same concept. This guide walks you through the binary search variations that appear constantly in interviews, with patterns and templates you can adapt.
Why Binary Search Variations Are Hard
Standard binary search on a sorted array is trivial. That's not what FAANG asks. Instead, they ask:
- "Search in rotated sorted array" (answer: modify the comparison logic)
- "Find peak element" (answer: apply binary search to a conceptual sorted sequence)
- "First/last position of target" (answer: use left/right biases carefully)
- "Search in 2D matrix" (answer: flatten the concept)
The difficulty isn't the algorithm—it's recognizing that these problems are disguised binary search problems and adapting the template correctly.
The Binary Search Mindset
Before diving into variations, understand the core mindset:
Binary search works when you can partition a search space into two parts where: (1) you can determine which part contains your answer, and (2) you can eliminate one part entirely.
In standard binary search on a sorted array, the array is naturally partitioned by the middle element. In variations, you might partition a rotated array, a matrix, or even a conceptual sequence. The algorithm remains: binary search.
Template: The Canonical Binary Search
All variations build from this template:
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Not foundKey insight: The comparison logic determines which half to discard. By changing the comparison, you adapt binary search to any variation.
Variation 1: Find First/Last Position of Target
Problem: Given a sorted array with duplicates, find the first and last position of target.
Approach: Run binary search twice—once to find the leftmost position, once to find the rightmost.
For leftmost position:
def find_first(arr, target):
left, right = 0, len(arr) - 1
result = -1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
result = mid
right = mid - 1 # Keep searching left
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return resultFor rightmost position:
def find_last(arr, target):
left, right = 0, len(arr) - 1
result = -1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
result = mid
left = mid + 1 # Keep searching right
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return resultKey insight: When you find the target, don't return immediately. Instead, record it and continue searching in the direction you want (left for first, right for last).
Variation 2: Search in Rotated Sorted Array
Problem: Array is sorted then rotated at some unknown pivot. Find a target.
Example: [4,5,6,7,0,1,2] is [0,1,2,4,5,6,7] rotated.
Approach: At any mid, one half is guaranteed to be properly sorted. Use that half to decide which way to narrow.
def search_rotated(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
# Left half is sorted
if arr[left] <= arr[mid]:
if arr[left] <= target < arr[mid]:
right = mid - 1 # Target is in sorted left half
else:
left = mid + 1 # Target is in right half
# Right half is sorted
else:
if arr[mid] < target <= arr[right]:
left = mid + 1 # Target is in sorted right half
else:
right = mid - 1 # Target is in left half
return -1Key insight: At any point, at least one half is guaranteed to be sorted (no rotation point in that half). Use this to decide direction.
Variation 3: Find Peak Element
Problem: Find any peak element (an element greater than its neighbors). Array may not be sorted.
Approach: Binary search on a conceptual "mountain"—if right neighbor is higher, peak is on the right; otherwise, on the left.
def find_peak(arr):
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] < arr[mid + 1]:
# Peak is on the right (including mid+1)
left = mid + 1
else:
# Peak is on the left (including mid)
right = mid
return leftKey insight: You don't need the array to be sorted. You need a property that lets you eliminate half the space. Here, the property is: "If right is higher, peak is on the right."
Variation 4: Find Minimum in Rotated Sorted Array
Problem: Rotated sorted array, find the minimum element.
Approach: Similar to searching in rotated array, but now you're searching for the rotation point (minimum).
def find_min(arr):
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] > arr[right]:
# Rotation point is on the right
left = mid + 1
else:
# Rotation point is on the left or is mid
right = mid
return arr[left]Key insight: The minimum is at the rotation point. Use comparisons to find where the sorted order breaks.
Variation 5: Search in 2D Matrix
Problem: 2D matrix where each row is sorted and the first element of each row > last element of previous row. Find a target.
Approach: Treat the matrix as a 1D sorted array. Use binary search indices and convert to 2D coordinates.
def search_matrix(matrix, target):
if not matrix:
return False
m, n = len(matrix), len(matrix[0])
left, right = 0, m * n - 1
while left <= right:
mid = (left + right) // 2
mid_value = matrix[mid // n][mid % n] # Convert 1D index to 2D
if mid_value == target:
return True
elif mid_value < target:
left = mid + 1
else:
right = mid - 1
return FalseKey insight: Flatten the 2D matrix conceptually. Row index = mid // n, column index = mid % n.
Variation 6: Search Range in 2D Matrix
Problem: Matrix where rows are sorted and the first element of each row is greater than the last element of the previous row. Find range of target positions.
Approach: Combine 2D matrix search with finding first/last position.
Run binary search to find the row containing the target, then run binary search within that row to find first and last positions.
Variation 7: Koko Eating Bananas
Problem: Koko eats n piles of bananas over h hours. Each hour, she picks a pile and eats at speed k. Find minimum speed k such that she finishes within h hours.
Approach: Binary search on the speed (not the array itself). For each speed, check if it's viable.
def min_eating_speed(piles, h):
def can_finish(speed):
hours = sum((pile + speed - 1) // speed for pile in piles)
return hours <= h
left, right = 1, max(piles)
while left < right:
mid = (left + right) // 2
if can_finish(mid):
right = mid # Try slower speeds
else:
left = mid + 1 # Need to go faster
return leftKey insight: Binary search on the answer (speed), not the input array. For each candidate answer, check if it's valid.
Variation 8: Capacity to Ship Packages
Problem: Ship packages in order. Each has a weight. Ship in d days. Capacity c must be at least max(weights). Find minimum c.
Approach: Binary search on capacity. For each capacity, check if all packages fit in d days.
def ship_within_days(weights, days):
def can_ship(capacity):
days_needed = 1
current_load = 0
for weight in weights:
if current_load + weight > capacity:
days_needed += 1
current_load = 0
current_load += weight
return days_needed <= days
left, right = max(weights), sum(weights)
while left < right:
mid = (left + right) // 2
if can_ship(mid):
right = mid
else:
left = mid + 1
return leftVariation 9: Split Array Largest Sum
Problem: Split array into k subarrays (contiguous). Minimize the maximum sum of any subarray.
Approach: Binary search on the answer (max sum). For each candidate, check if k subarrays suffice.
def split_array(nums, k):
def min_subarrays_needed(max_sum):
subarrays = 1
current_sum = 0
for num in nums:
if current_sum + num > max_sum:
subarrays += 1
current_sum = 0
current_sum += num
return subarrays
left, right = max(nums), sum(nums)
while left < right:
mid = (left + right) // 2
if min_subarrays_needed(mid) <= k:
right = mid
else:
left = mid + 1
return leftBinary Search on Answer Pattern
Variations 7, 8, 9 follow a pattern: Binary search on the answer.
Instead of searching within input data, you search over a range of possible answers. For each candidate answer, you ask: "Is this answer valid?" If yes, try smaller; if no, try larger.
This pattern applies to many problems:
- Minimize maximum (split array problems)
- Maximize minimum (distribute resources)
- Find feasibility threshold
Common Binary Search Mistakes
Mistake 1: Wrong loop condition. Should it be left <= right or left < right? Depends on whether you want to return left or right at the end.
Mistake 2: Integer overflow in mid calculation. Use mid = left + (right - left) // 2 instead of (left + right) // 2.
Mistake 3: Not adjusting comparison logic. In variations, the comparison determines everything.
Mistake 4: Assuming the input is sorted. Some variations work on unsorted data if you have a property that lets you eliminate half the space.
Mistake 5: Off-by-one errors. Especially with first/last position and converted indices.
Debugging Binary Search
If your binary search doesn't work:
- Check loop condition. Does it terminate correctly?
- Check mid calculation. Is the middle index correct?
- Check comparison logic. Does it correctly identify which half contains your answer?
- Check termination state. What does
leftorrightrepresent when the loop ends? - Trace by hand. On a small example, follow the algorithm step-by-step.
Interview Tips
- State your approach clearly. "This is a binary search problem. I'll search on X and use Y as the comparison."
- Explain the comparison logic. "If this condition is true, the answer is on the right half because..."
- Test edge cases. Empty array, single element, all duplicates, target not found.
- Know when not to use binary search. If the search space doesn't partition cleanly, use a different approach.
Practicing Binary Search Effectively
- Do 20-30 binary search problems on LeetCode.
- For each, identify which variation it is.
- For each, write the algorithm clearly before coding.
- Code it, test it, optimize space and time.
- Teach the solution to someone else.
Preparation for Your Next Interview
Binary search variations require deep understanding and practice to recognize and code flawlessly. You need to internalize the patterns so they're automatic during interviews. If you're doing mock interviews and want real-time feedback on your binary search solutions, Phantom Code is perfect. It's an invisible AI assistant that listens to your interviewer during practice and provides instant algorithm suggestions, implementation hints, and complexity analysis through a chat interface. It supports all major languages and is completely undetectable by screen-sharing. Plans start at ₹499/month. Visit phantomcode.co.
Final Thoughts
Binary search variations are consistently asked because they test: pattern recognition, algorithmic thinking, and careful implementation. Master the template and the variations listed above, and you'll be ahead of most candidates. Practice until you can recognize a binary search problem instantly and code it without debugging.