Junior 5 min · March 06, 2026

Binary Search Interview Problems — Off-by-One Traps

Using < instead of <= when left == mid breaks rotated array search silently.

N
Naren · Founder
Plain-English first. Then code. Then the interview question.
About
 ● Production Incident 🔎 Debug Guide
Quick Answer
  • Binary search eliminates half the search space per guess — O(log n) instead of O(n)
  • Pattern 1: Standard value search on sorted array (LeetCode 704)
  • Pattern 2: Boundary search for first/last occurrence in duplicates (LeetCode 34)
  • Pattern 3: Rotated array search — determine sorted half and decide (LeetCode 33)
  • Pattern 4: Answer-space search — binary search on answer range, not input (LeetCode 875)
  • Performance: 1 billion sorted elements require at most 31 comparisons — but off-by-one bugs cause silent infinite loops in production
Plain-English First

Imagine you're looking up a word in a physical dictionary. You don't start from page 1 — you crack it open in the middle, decide whether your word comes before or after that page, then repeat with the surviving half. That's binary search: you eliminate half the possibilities with every single guess. A 1000-page dictionary only needs about 10 guesses. That's the power — and that's exactly what interviewers are testing when they ask you to 'find something efficiently in a sorted structure'.

Binary search shows up in roughly 15-20% of technical screening rounds at top tech companies — not because it's exotic, but because it's a clean signal for how a candidate thinks about elimination, boundaries, and edge cases under pressure. Miss the pattern and you'll write an O(n) linear scan where an O(log n) search was expected. Spot it and you look like the engineer who actually understands algorithmic trade-offs.

The real problem isn't the algorithm itself — most people can recite 'split in half, compare, repeat'. The problem is recognizing WHEN to apply it, and then getting the boundary conditions exactly right without an off-by-one bug that only surfaces on arrays of length 1 or 2. Interviewers know this, which is why they love edge cases like single-element arrays, all-duplicate arrays, and rotated sorted arrays.

By the end of this article you'll be able to identify the four core binary search patterns by sight, implement each one without looking up the boundary conditions, and explain your reasoning out loud — which is exactly what interviewers want to hear. We'll go from the textbook template all the way through rotation, condition-based search, and answer-space binary search with full runnable code for each.

The Template That Eliminates Off-By-One Bugs Forever

Every binary search variant is a specialization of one template. Until you've internalized this template so deeply that you can write it in your sleep, you'll keep making subtle off-by-one errors that cause infinite loops or miss the target by one index.

The key design decision in any binary search is: what does your loop invariant guarantee? The invariant we'll use is this — the answer, if it exists, is always inside the closed interval [left, right]. That single rule dictates every boundary choice that follows.

When left == right there's exactly one candidate left. That's why the loop condition is left <= right, not left < right. And when you calculate mid, you use left + (right - left) / 2 instead of (left + right) / 2 — both give the same index, but the second one silently overflows when left and right are large integers, a bug that killed a famous Java binary search implementation in the JDK for nearly a decade.

The moment you find target at mid, you return immediately. If target < array[mid], the right half is useless, so right = mid - 1. If target > array[mid], the left half is useless, so left = mid + 1. This is the foundation every other pattern builds on.

io/thecodeforge/search/ClassicBinarySearch.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package io.thecodeforge.search;

public class ClassicBinarySearch {

    /**
     * Standard iterative Binary Search.
     * LeetCode 704: Binary Search
     * 
     * @param nums   Sorted array of integers
     * @param target Integer to find
     * @return Index of target, or -1 if not found
     */
    public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) return -1;

        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            // Use unsigned right shift or (left + (right - left) / 2) to prevent overflow
            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return -1;
    }
}
Output
Standard O(log n) execution.
Watch Out: The Overflow Trap
Never write mid = (left + right) / 2 in an interview. If left = 1_000_000_000 and right = 1_500_000_000, that addition overflows a 32-bit int and produces a negative mid. Always use mid = left + (right - left) / 2. It's one of the most famous bugs in production code — mention you know about it and you'll impress any interviewer.
Production Insight
The overflow bug in (left+right)/2 stayed in Java's Arrays.binarySearch for years.
It only crashes when left+right exceeds Integer.MAX_VALUE — rare for small arrays, but common in large datasets.
Rule: always use mid = left + (right - left)/2 — safe, no overflow, one extra subtraction costs nothing.
Key Takeaway
The loop invariant must be: the answer lives inside [left, right].
Use left <= right so single-element arrays are processed.
Never use (left+right)/2 — always left + (right-left)/2.
Choosing Classic Binary Search vs Other Patterns
IfArray is sorted and no duplicates
UseUse classic binary search — return on first match.
IfArray sorted but has duplicates
UseSwitch to boundary search pattern (next section).
IfArray is rotated (pivot at unknown point)
UseUse rotated array search — detect sorted half each iteration.
IfNo array to search; answer range is monotonic
UseUse answer-space binary search — binary search on possible answers.

Finding Boundaries: First and Last Position of a Duplicated Target

Once you've nailed the classic template, the first upgrade interviewers throw at you is: 'What if the array has duplicates? Find the first occurrence, or the last occurrence.' This is LeetCode 34, and it's a direct test of whether you understand binary search deeply or just memorized the basic version.

The trick is to NOT return the moment you find the target. Instead, you record the current mid as a candidate answer, then deliberately push the search boundary to keep looking. For the first occurrence you push right = mid - 1 (keep searching left). For the last occurrence you push left = mid + 1 (keep searching right).

This turns a single-target search into a boundary search. The loop still terminates — left and right still converge — but now instead of exiting early you let the loop exhaust all possibilities, always keeping the best answer you've seen so far.

This pattern has a name: Left Boundary Binary Search and Right Boundary Binary Search. Recognizing them as named patterns rather than one-off tricks is what lets you adapt quickly when interviewers change the constraint mid-question.

io/thecodeforge/search/BoundarySearch.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package io.thecodeforge.search;

public class BoundarySearch {

    /**
     * LeetCode 34: Find First and Last Position of Element in Sorted Array
     */
    public int[] searchRange(int[] nums, int target) {
        int[] result = {-1, -1};
        result[0] = findBoundary(nums, target, true);
        result[1] = findBoundary(nums, target, false);
        return result;
    }

    private int findBoundary(int[] nums, int target, boolean isFirst) {
        int left = 0, right = nums.length - 1;
        int ans = -1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                ans = mid;
                if (isFirst) {
                    right = mid - 1; // Shrink towards the left
                } else {
                    left = mid + 1;  // Shrink towards the right
                }
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return ans;
    }
}
Output
Input: [5,7,7,8,8,10], target=8 -> Output: [3,4]
Interview Gold: Combine Both for Range Queries
Interviewers often ask 'how many times does X appear?' instead of directly asking for first/last position — it's the same problem in disguise. Call findFirstOccurrence and findLastOccurrence, then return lastIndex - firstIndex + 1 (or 0 if firstIndex == -1). Naming the sub-problems out loud before coding shows structured thinking, which is worth more than writing fast.
Production Insight
In production, boundary search is used to find the exact range of log entries with the same timestamp.
The common mistake is forgetting to handle the case where the target never appears — ans stays -1.
Rule: always initialize ans to -1 before the loop, and check it after the loop before using the result.
Key Takeaway
Don't return early when you find the target in a duplicate array.
Record the index as ans, then keep narrowing the side you're searching.
The loop ends when left > right — ans holds the best result seen.
When to Use Boundary Search
IfNeed first or last occurrence of duplicate values
UseUse one-sided narrow: for first, right = mid - 1; for last, left = mid + 1.
IfNeed count of occurrences
UseCall first and last, compute count = last - first + 1 (or 0 if not found).

Searching a Rotated Sorted Array — The Classic Hard-Mode Variant

Here's where interviewers separate people who 'know binary search' from people who truly understand it. A rotated sorted array is an array like [40, 55, 63, 7, 18, 29] — it was originally sorted but has been rotated around a pivot. Half the array is still sorted. That's the key insight.

At every mid-point you can determine in O(1) which half is sorted — just compare array[left] with array[mid]. If array[left] <= array[mid], the left half is cleanly sorted. Otherwise, the right half is. Once you know which half is sorted, you can check in O(1) whether the target falls inside that sorted half. If yes, search there. If no, search the other half.

You never need to find the pivot explicitly. The binary search logic handles everything in one pass. That's the elegant part — and it's also what trips people up who try to pre-compute the pivot index before searching. Two passes where one will do is a sign of incomplete understanding, and interviewers notice.

io/thecodeforge/search/RotatedSearch.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package io.thecodeforge.search;

public class RotatedSearch {

    /**
     * LeetCode 33: Search in Rotated Sorted Array
     */
    public int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) return mid;

            // Left half is sorted
            if (nums[left] <= nums[mid]) {
                if (target >= nums[left] && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } 
            // Right half is sorted
            else {
                if (target > nums[mid] && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return -1;
    }
}
Output
Input: [4,5,6,7,0,1,2], target=0 -> Output: 4
Interview Gold: Draw It Before Coding
Before writing a single line of code for a rotated array problem, draw the array on a whiteboard and mark mid, left, and right. Showing the interviewer that you reason spatially before coding is a massive differentiator. Say out loud: 'I need to figure out which half is cleanly sorted first.' That single sentence demonstrates you know the algorithm at a conceptual level, not just by memory.
Production Insight
In production, rotated array patterns appear in time-series data that has been shifted due to timezone offsets.
The bug that crashes production most often is using < instead of <= when comparing nums[left] <= nums[mid] — causes misclassification of sorted half when mid equals left.
Rule: always use <= for the sorted-half check; a single-element range is still sorted.
Key Takeaway
You never need to find the pivot explicitly — just determine which half is sorted each iteration.
Use <= when checking if left half is sorted.
Test with length-2 arrays: that's where the <= vs < bug hides.

Answer-Space Binary Search — When the Input Isn't Even an Array

This is the pattern that separates intermediate from advanced binary search practitioners — and it trips up even experienced engineers. Answer-space binary search applies when you can't binary search the input directly, but you CAN binary search the space of possible answers.

The template is: define a minimum and maximum possible answer (your left and right pointers). Write a feasibility function that checks 'is this candidate answer good enough?'. Then binary search over the answer space, always recording the best valid answer found so far. This is the most powerful and least-recognized form of binary search in interview settings.

io/thecodeforge/search/KokoEatingBananas.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package io.thecodeforge.search;

public class KokoEatingBananas {

    /**
     * LeetCode 875: Koko Eating Bananas
     * Binary search on the 'speed' (answer space).
     */
    public int minEatingSpeed(int[] piles, int h) {
        int left = 1, right = 1_000_000_000;
        int ans = right;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (canFinish(piles, h, mid)) {
                ans = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }

    private boolean canFinish(int[] piles, int h, int k) {
        long totalHours = 0;
        for (int p : piles) {
            totalHours += (p + k - 1) / k; // Ceiling division
        }
        return totalHours <= h;
    }
}
Output
Returns the minimum integer k such that Koko can eat all bananas within h hours.
Pro Tip: Spotting Answer-Space Problems in the Wild
If the problem says 'minimize the maximum' or 'maximize the minimum' and involves some kind of allocation or scheduling — it's almost certainly an answer-space binary search problem. The giveaway is monotonicity: ask yourself 'if X works, does X+1 also work?' If yes, you've got a binary searchable answer space. State this explicitly during the interview and your interviewer will know you recognize the pattern.
Production Insight
Answer-space binary search is used in production for capacity planning: find minimum server count to handle peak load.
The tricky part is setting the initial bounds — left must be the minimum feasible answer (never 0), right must cover worst case.
Rule: derive left from problem constraints (e.g., max pile size for Koko) and right from sum of all resources (e.g., max bananas in 1 hour).
Key Takeaway
When you can test feasibility in O(n) and the answer is monotonic, binary search the answer space.
Define left as the minimum plausible answer, right as the maximum plausible answer.
Record the best valid answer found and continue narrowing — don't return on first 'feasible'.

Finding Square Root Using Binary Search — Integer Square Root with Precision

A classic answer-space binary search example: find the integer square root of a non-negative integer x. You don't need Math.sqrt or Newton's method — binary search over [0, x] works beautifully and is often what interviewers expect for LeetCode 69 (Sqrt(x)).

The feasibility function is simple: check if mid * mid <= x. If yes, move left to mid + 1 (the square root could be larger). If no, move right to mid - 1. Record the candidate answer (mid) each time the check passes, because the last valid mid before the loop ends is the integer square root.

This problem is a perfect warm-up before tackling more complex answer-space problems like Koko Eating Bananas or Split Array Largest Sum. It's also a good test of overflow handling — mid * mid can overflow int if x is large. Use long for the multiplication.

io/thecodeforge/search/SqrtBinarySearch.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package io.thecodeforge.search;

public class SqrtBinarySearch {

    /**
     * LeetCode 69: Sqrt(x)
     * Returns the integer floor of square root.
     */
    public int mySqrt(int x) {
        if (x == 0) return 0;
        int left = 1, right = x, ans = 0;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            // Use long to avoid overflow when mid * mid
            if ((long) mid * mid <= (long) x) {
                ans = mid;   // mid is a candidate
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return ans;
    }
}
Output
mySqrt(8) -> 2 (since 2*2=4 <= 8, 3*3=9 > 8)
Why Binary Search Works for Square Root
  • The answer space is [0, x] — but we can start left at 1 because sqrt(0)=0 is trivial.
  • Feasibility: mid * mid <= x — if true, the true sqrt is at least mid.
  • Overflow trap: mid * mid exceeds int range for x > 46340. Cast to long to avoid silent rollover.
  • Why record ans inside loop? Because the last time the condition passes is the integer floor of sqrt.
Production Insight
This same pattern powers many approximation algorithms in computational geometry and numeric libraries.
For floating-point square root, binary search with a precision threshold (e.g., 0.0001) replaces equality check.
Rule: when the answer space is numeric and monotonic, binary search is your simplest correct implementation.
Key Takeaway
Square root via binary search is the ideal answer-space teaching example — it's simple, has an overflow trap, and generalises to any monotonic feasibility function.
Always cast mid*mid to long to avoid overflow before Java 8's Math.multiplyHigh or Java 9's Math.floorDiv.

Interviewers often combine matrix traversal with binary search. LeetCode 240 (Search a 2D Matrix II) presents a matrix where rows and columns are sorted independently. The trick is to start from the top-right corner: you can eliminate an entire row or column in each step.

But there's also a binary search pattern here: if you treat each row as a sorted array, you could binary search each row individually — O(m log n). Or you could use the 'staircase' approach which is O(m+n). The interview trick is to recognise when the matrix is 'row and column sorted' vs 'fully sorted row-major' (LeetCode 74). For fully sorted row-major, you can flatten the matrix logically (using modulo arithmetic) and do one binary search in O(log(m*n)).

Know which variant you face: if the first element of each row is > last element of previous row, it's row-major sorted and you can do a true 2D binary search. If only rows and columns are sorted individually, use the top-right elimination method.

io/thecodeforge/search/MatrixSearch.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package io.thecodeforge.search;

public class MatrixSearch {

    /**
     * LeetCode 240: Search a 2D Matrix II (row and column sorted)
     * Top-right corner elimination O(m+n)
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) return false;
        int row = 0, col = matrix[0].length - 1;

        while (row < matrix.length && col >= 0) {
            if (matrix[row][col] == target) {
                return true;
            } else if (matrix[row][col] < target) {
                row++; // all elements in this row to the left are smaller, so go down
            } else {
                col--; // all elements below in this column are larger, so go left
            }
        }
        return false;
    }

    /**
     * LeetCode 74: Search a 2D Matrix (fully sorted row-major)
     * Single binary search over flattened array
     */
    public boolean searchMatrixRowMajor(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) return false;
        int m = matrix.length, n = matrix[0].length;
        int left = 0, right = m * n - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            int midVal = matrix[mid / n][mid % n];
            if (midVal == target) return true;
            else if (midVal < target) left = mid + 1;
            else right = mid - 1;
        }
        return false;
    }
}
Output
searchMatrix([[1,4,7,11],[2,5,8,12],[3,6,9,16]], target=5) -> true
Critical Distinction: Fully Sorted vs Row/Column Sorted
If the problem statement says 'each row is sorted and the first element of each row is greater than the last element of the previous row', you can flatten the matrix. If it only says 'rows are sorted from left to right and columns from top to bottom', use the top-right elimination — otherwise you'll miss the target by assuming global ordering.
Production Insight
Matrix search appears in production when analyzing sensor data arrays arranged in time-space grids.
A common mistake is using the O(m log n) row-wise binary search when an O(m+n) elimination works — not a correctness bug, but interviewers will ask why you didn't use the optimal approach.
Rule: always ask the interviewer 'is the matrix fully sorted row-major, or just row/column sorted?' before coding.
Key Takeaway
Fully sorted matrix (row-major) → flatten and binary search in O(log(m+n)).
Row and column sorted only → top-right corner elimination in O(m+n).
Never assume global sorted order — ask the question explicitly.
● Production incidentPOST-MORTEMseverity: high

Off-by-One in Rotated Array Search Causes Null Pointer in Production Indexer

Symptom
Search engine returned stale results for documents updated within the last 24 hours. No errors visible in logs — the crash happened after the response was already sent.
Assumption
The team assumed the rotated array implementation was correct because it passed the initial test suite with arrays of size 3-10.
Root cause
In the line if (nums[left] <= nums[mid]), the condition used < instead of <=. When left == mid (two-element array), the left half was incorrectly identified as unsorted, causing the search to skip the target in the right half and eventually throw a NullPointerException when mid went out of bounds on the recursion recovery path.
Fix
Changed the condition to nums[left] <= nums[mid] and added a unit test that specifically tests arrays of length 2 with the target at the second position.
Key lesson
  • Always test rotated array search on arrays of length 1 and 2 — those are where boundary conditions hide.
  • Use <= when checking if a half is sorted by comparing nums[left] with nums[mid]; if left == mid, a single-element range is still sorted.
  • Never assume test coverage on a variety of sizes is enough — edge-case arrays are where off-by-one bugs live.
Production debug guideSymptom → Action guide for the most common binary search implementation failures4 entries
Symptom · 01
Infinite loop when search space is 2 elements
Fix
Check loop condition: use while (left <= right) not left < right. Ensure that when target != array[mid], you set right = mid - 1 or left = mid + 1 — never leave right = mid without also adjusting.
Symptom · 02
Function returns -1 for single-element array that contains the target
Fix
The loop exits before checking the final element. If using left < right, add a post-loop check: return array[left] == target ? left : -1. Better yet, switch to left <= right.
Symptom · 03
Boundary search (first/last) returns wrong position for duplicate values
Fix
Debug by printing left, right, mid, ans after each iteration. Verify that after finding target == array[mid], you don't return early — instead record ans = mid and continue narrowing the side you're searching.
Symptom · 04
Rotated array search fails on arrays like [2,1], target=1
Fix
Check the sorted-half detection: if (array[left] <= array[mid]). For length-2 arrays, mid=0, so array[0] <= array[0] must be true to correctly identify left half as sorted. If you used <, left half is misclassified as unsorted.
★ Quick Debug Cheat Sheet for Binary Search in InterviewsWhen your binary search isn't working in a whiteboard interview, run through these checks in order.
Infinite loop
Immediate action
Pause and add a print of left, right, mid before the next iteration.
Commands
Check loop condition: is it `left <= right`?
Check mid update: did you write `mid = left + (right - left) / 2`?
Fix now
If left and right aren't moving, ensure you set right = mid - 1 or left = mid + 1 after comparing array[mid] with target.
Returns -1 when target exists+
Immediate action
Trace the loop on a 3-element array. Write down left, right, mid on paper.
Commands
Check if loop exits early: using `while (left < right)`?
After loop, is there a post-loop check for array[left]?
Fix now
Switch to while (left <= right) — it eliminates the need for post-loop check and handles the single-element case.
Boundary search returns wrong index+
Immediate action
Check whether you're updating `ans` correctly after finding target.
Commands
When array[mid] == target, do you set `ans = mid` before narrowing?
If searching for first occurrence, did you set `right = mid - 1`?
Fix now
Make sure you don't return on first match — keep narrowing and update ans until the loop ends.
Binary Search Patterns Quick Reference
PatternWhen to Use ItKey Condition to CheckGotcha
Classic Binary SearchSorted array, find exact valuearray[mid] == targetMust have no duplicates or don't care which occurrence you get
Left/Right Boundary SearchSorted array with duplicates, find first/last positionRecord mid, keep searching left (or right)Must NOT return early when target found — keep going
Rotated Array SearchArray was sorted, then rotated at unknown pivotWhich half is cleanly sorted? Is target inside it?Off-by-one in condition: use <= for left check, <= for right check
Answer-Space Binary SearchNo array to search; answer range is monotonicIs this candidate answer feasible? (Yes → go lower, No → go higher)Hardest part is defining left/right bounds of answer space correctly
Square Root Binary SearchFind integer square root; prototype for answer-space problemsmid * mid <= x (cast to long to avoid overflow)Overflow if using int multiplication; post-loop ans holds floor
2D Matrix Search (row/column sorted)Search in matrix where rows and columns individually sortedStart top-right: compare with target, eliminate row or columnDon't flatten if only row/col sorted — use elimination; for full row-major sort, flatten

Key takeaways

1
Every binary search variant shares one invariant
the answer lives inside [left, right]. Every boundary decision follows from that invariant — memorize the logic, not the code.
2
For duplicate arrays, resist the urge to return early when you find the target. Record it as a candidate answer, then keep pushing the boundary in your search direction.
3
In a rotated sorted array you don't need to find the pivot. Determine which half is cleanly sorted at every step
that's the only local information you need to make the right decision.
4
Answer-space binary search is the most powerful and most overlooked pattern. If a problem says 'minimize the maximum' or 'maximize the minimum' with a feasibility check, binary search the answer range
not the input.
5
For matrix search, ask whether the matrix is fully sorted (row-major) or just row + column sorted. The answer determines your algorithm
flat binary search vs top-right elimination.

Common mistakes to avoid

5 patterns
×

Using left < right instead of left <= right

Symptom
Loop exits when left == right, skipping the last remaining candidate. Always returns -1 for single-element arrays or arrays where target is at the final converged position.
Fix
Use while (left <= right) and trust that the body handles the single-element case correctly.
×

Writing right = mid instead of right = mid - 1 when array[mid] != target

Symptom
Infinite loop when search space is two elements (left == mid). The range never shrinks because mid has already been checked and excluded.
Fix
Always use right = mid - 1 and left = mid + 1 in the classic template, because you've already eliminated mid as a candidate.
×

In answer-space binary search, setting initial bounds wrong (e.g., left = 0 for ship capacity)

Symptom
Feasibility function returns false for left, but the real bug is the search never converges correctly. The algorithm may exit early with wrong answer.
Fix
Derive left from domain constraints (minimum meaningful answer) and right from worst-case upper bound. State these derivations out loud during an interview.
×

In rotated array search, using `nums[left] < nums[mid]` instead of `<=`

Symptom
When left == mid (array length 2), left half is mistakenly identified as unsorted, causing the search to look in wrong half. Leads to index out of bounds or wrong result.
Fix
Always use nums[left] <= nums[mid] to correctly classify a single-element range as sorted.
×

In boundary search, returning early when target is found instead of continuing to narrow

Symptom
Returns an occurrence of target, but not necessarily the first or last. Only works if you don't care about leftmost/rightmost position.
Fix
Record the found index as ans, then continue narrowing: for first, set right = mid - 1; for last, set left = mid + 1. Return ans after the loop.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
LeetCode 33: Search in Rotated Sorted Array. How do you handle the searc...
Q02SENIOR
LeetCode 34: Find First and Last Position of Element in Sorted Array. Wh...
Q03SENIOR
LeetCode 875: Koko Eating Bananas. How do you determine the initial 'Rig...
Q04SENIOR
LeetCode 153: Find Minimum in Rotated Sorted Array. How does the compari...
Q05JUNIOR
LeetCode 69: Sqrt(x). Why do we need to use long for the multiplication ...
Q01 of 05SENIOR

LeetCode 33: Search in Rotated Sorted Array. How do you handle the search when you cannot find the pivot point explicitly in O(1)?

ANSWER
You don't need the pivot. At each iteration, compare nums[left] with nums[mid]. If nums[left] <= nums[mid], the left half is sorted. Check if target lies in that sorted range; if yes, search left half; otherwise, search right half. If the left half is not sorted, the right half must be sorted (since the array is rotated), and you apply similar logic. This single-pass approach avoids a separate pivot find step and runs in O(log n).
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
How do I know when to use binary search in a coding interview?
02
What is the difference between left < right and left <= right in binary search?
03
Why does binary search only work on sorted arrays?
04
How can I avoid overflow when computing mid or mid*mid?
05
What is the most common mistake in binary search interviews?
🔥

That's Coding Patterns. Mark it forged?

5 min read · try the examples if you haven't

Previous
Prefix Sum Interview Problems
12 / 17 · Coding Patterns
Next
Heap Interview Problems