---
title: "Binary search problems, worked"
url: "https://georgeliinternships.com/interview-prep/coding/binary-search.md"
canonical_url: "https://georgeliinternships.com/interview-prep/coding/binary-search"
last_updated: "2026-12-01"
type: "guide"
summary: "Binary search for coding interviews: the halving loop, common bugs, complexity, problems from easy to hard and four checked practice problems."
related: ["https://georgeliinternships.com/interview-prep.md", "https://georgeliinternships.com/methodology.md", "https://georgeliinternships.com/roles.md"]
---

# Binary search in coding interviews: how it works and problems by difficulty

> **For AI agents:** the complete index of George Li Internships pages is [llms.txt](https://georgeliinternships.com/llms.txt). Every page is also served as markdown at its URL plus .md.

Binary search for coding interviews: the halving loop, common bugs, complexity, problems from easy to hard and four checked practice problems.

Binary search appears across phone screens and onsite coding rounds because it tests how cleanly you narrow a search space and guard boundary conditions. Use this guide to review how the algorithm works, compare its complexity tradeoffs, and practice 50 classic problems from easy to hard.

## Why interviewers rely on binary search problems

Software engineering interviews return to binary search again and again for a simple reason: the core loop looks short on paper, yet tiny mistakes with midpoints, inequalities, or empty intervals break a solution immediately. Hiring teams also value binary search because it underpins dozens of harder algorithms, from finding decision thresholds to optimizing dynamic programming transitions.

Before diving into all 50 practice problems, check whether you can handle six standard prompts that show up in early and mid-stage technical interviews:

- Standard lookup: You receive an integer list sorted from smallest to largest along with a target number. Return the zero-based position of that target, or return -1 when it does not appear.
- Minimum in a rotated sorted array: A strictly ascending list of distinct numbers was shifted circularly at an unknown pivot. Locate the smallest value while keeping runtime logarithmic.
- Sorted matrix lookup: Search for a number inside a rectangular grid where every row increases left to right and the opening entry of each row exceeds the final entry above it.
- Insertion slot search: Given unique sorted integers and a query value, output the matching index if present, or the exact slot where placing that value preserves sorted order in O(log n) steps.
- Target in a rotated array: A sorted array may have been rotated around some pivot index. Return the index where a target integer lives, or -1 if it is absent.
- Median of two sorted lists: Given two ordered arrays with lengths m and n, compute their combined median in O(log(m + n)) time without merging both lists linearly.

## How binary search works and where code usually breaks

Binary search cuts your remaining work in half on every comparison. To pull that off, the underlying container must satisfy two rules: the items must follow a predictable order, and jumping to any position must take constant time. Out of the basic linear containers, only a sorted array gives you both properties. A linked list can hold sorted values, yet reaching its midpoint forces a linear walk.

### The step-by-step halving loop

1. Set two boundary pointers covering the active interval, typically left at 0 and right at length minus 1.
2. Compute the center index inside the current interval and read the value stored there.
3. If that center value matches your target, stop and return the center index right away.
4. If the target is smaller, move the right boundary just before the center; if the target is larger, move the left boundary just past the center.
5. Continue narrowing until the pointers cross. Once the active interval holds zero items, return -1 to report that the target is missing.

Walk through a short concrete trace to see the pointers move. Suppose your sorted array is [2, 5, 8, 11, 14, 19, 23] and you want the index of 14. On pass one, left is 0 and right is 6, so the midpoint is index 3, which holds 11. Because 14 exceeds 11, you discard indices 0 through 3 and move left to 4.

On pass two, the active window spans index 4 to index 6, giving a midpoint at index 5 with value 19. Since 14 is smaller than 19, you move right to 4. On pass three, left and right both equal 4, so index 4 becomes the midpoint. That position contains 14, and your function returns 4.

### Two implementation bugs to watch out for

When coding in Python, Java, or C++, two small syntax choices separate bug-free implementations from subtle failures:

- Safe midpoint arithmetic: Writing (left + right) / 2 creates two hazards. First, in fixed-width integer languages like Java and C++, adding two huge indices can wrap past the maximum signed integer and trigger an overflow. Computing left + (right - left) / 2 avoids that trap. Second, languages like Python 3 turn single-slash division into a float, so always use integer floor division (//) or an explicit floor helper so your midpoint stays a valid array index.
- Inclusive loop condition: Check the single-element case carefully. In the trace above, the third iteration narrowed the search down to index 4 on both ends. Had the loop tested left < right instead of left <= right, execution would have exited early and missed 14 completely. Using left <= right ensures a one-element window still gets inspected.

### Practical use cases in production and interviews

- Fast point lookups at scale: Searching an ordered index of 1,000,000 entries finishes in roughly 20 comparisons because 2 raised to the 20th power exceeds one million.
- Threshold and range slices: Given a sorted record of household net worth or employee pay, one binary search locates the earliest entry meeting a cutoff, letting you read every qualifying record from that index through the end of the array.
- Insertion and removal slots: Any system maintaining an ordered array relies on binary search to pinpoint where a new record belongs or which index holds an element queued for deletion.

### Comparing binary search with alternative structures

Binary search is fast, though not always the fastest option on raw membership checks. Hash tables answer whether a key exists in O(1) average time. However, hashing scrambles order, so a hash table cannot tell you the closest smaller or larger value, cannot fetch the minimum or maximum in constant time, and cannot slice out all entries inside a range.

Unsorted arrays flip the tradeoff: appending or swapping out items takes constant time, while searching takes linear time. Even though scanning contiguous memory linearly gives the CPU cache great spatial locality, cache hits cannot catch up with logarithmic halving once arrays grow large. Sorted arrays pay the opposite tax, forcing O(n) element shifts whenever you insert or delete outside the end.

Binary search trees avoid shifting elements during updates, yet an unbalanced tree can turn into a single skewed chain where every node holds one child, pulling lookup speed down to linear time. Self-balancing trees restore O(log2 n) search, though scanning ranges takes more pointer hops and reading the smallest or largest key drops from constant time to logarithmic time unless cached separately.

| Structure | Search time | Insert or delete | Range and neighbor queries |
| --- | --- | --- | --- |
| Sorted array with binary search | O(log2 n) | O(n) average due to shifting | Strong; O(log2 n) bounds and O(1) min/max |
| Hash table | O(1) average | O(1) average | Not supported without sorting |
| Unsorted array | O(n) linear scan | O(1) at tail | Requires full O(n) pass |
| Balanced binary search tree | O(log2 n) | O(log2 n) | Supported via in-order traversal |
*Tradeoffs across common search structures*

## Complexity cheat sheet and related tree mechanics

Memorizing Big-O symbols without knowing why they hold backfires as soon as an interviewer tweaks the constraints. Aim to explain each bound directly from what the code touches at runtime and in memory.

| Operation | Best case | Average case | Worst case | Extra space |
| --- | --- | --- | --- | --- |
| Binary search lookup | O(1) | O(log2 n) | O(log2 n) | O(1) iterative |
| Min or max in sorted array | O(1) | O(1) | O(1) | O(1) |
| Range boundary query | O(1) | O(log2 n) | O(log2 n) | O(1) |
| Sorted array insert or delete | O(1) at tail | O(n) | O(n) | O(1) in-place |
| Balanced BST search | O(1) | O(log2 n) | O(log2 n) | O(1) iterative |
*Binary search and sorted container complexity summary*

### Time and space bounds explained

Because every iteration divides the candidate count by two, both average and worst-case lookups finish in O(log2 n) time. The worst case happens when the target is absent and the search window shrinks all the way to zero. Only one lucky case hits O(1): when the initial midpoint already matches the target. Finding the minimum or maximum element in a sorted array takes O(1) since those values sit at index 0 and index n - 1, while locating range boundaries takes O(log2 n).

Iterative binary search needs O(1) extra space. Your function tracks only a handful of index variables (left, right, and mid), so memory usage stays flat whether your array holds ten integers or ten million.

### How sorted arrays compare with binary search trees

In a sorted array, appending to the end or popping the very last item takes constant work. Inserting or deleting anywhere earlier forces every item to the right of that position to shift one index forward or backward, producing an O(n) average cost.

Searching a binary search tree mirrors array halving step for step:

1. Begin at the root node and check whether its key equals the target.
2. If the target is smaller, move to the left child subtree; if larger, move to the right child subtree.
3. Repeat until you hit a matching node or reach an empty child pointer, returning -1 when absent.

Picture a small tree whose root holds 10, with a right child of 18 whose own left child holds 14. Searching for 14 starts at 10 (too small, go right), checks 18 (too big, go left), and lands on 14 at the leaf. Each level eliminates half of a balanced tree in O(log2 n) steps, and once you locate an open child slot, attaching a new leaf node like 7 takes constant pointer rewiring without shifting neighbors.

## Easy binary search questions for phone screens

Early phone screens often ask straightforward binary search prompts where you explain your reasoning aloud or write concise code without complex tooling. Resist the urge to memorize solutions across all 50 problems. Interviewers routinely invent custom twists you will not find online. Instead, replicate interview pressure: set a timer, write a solution from scratch without notes, inspect a walkthrough only if you stall, and immediately tackle the next prompt on your own rather than reading several solutions in a row.

1. Search insert position: Given unique sorted integers and a target, return its index or the insertion slot using left after the loop exits.
2. Integer square root: Compute the floored whole-number square root of x by binary searching 0 to x and checking mid * mid safely.
3. First bad version: Given releases 1 through n and a failure check API, find the earliest broken build with minimal calls.
4. Intersection of two arrays: Sort one list, binary search each unique value from the other, and collect shared integers without duplicates.
5. Valid perfect square: Check whether a positive integer equals k * k for some integer k by searching 1 to num // 2.
6. Guess number higher or lower: Locate a secret integer in 1 to n using feedback (-1, 0, or 1) from an external guess helper.
7. Arranging coins: Stack n coins into staircase rows of lengths 1, 2, ..., k and find the largest k where k * (k + 1) / 2 <= n.
8. Classic binary search: Run an iterative loop on an ascending integer array to return the target index or -1 if absent.
9. Smallest letter greater than target: Search sorted lowercase letters for the earliest character above target, wrapping to index 0 when needed.
10. Peak index in a mountain array: In a unimodal array that climbs then falls, compare mid against mid + 1 to isolate the summit.
11. Count negative numbers in a sorted matrix: Walk rows sorted non-increasingly and binary search the first negative value per row (or trace from top-right).
12. Distance value between two arrays: Sort the second array and binary search [x - d, x + d] to count elements in array one outside that band.
13. Kth missing positive number: Binary search the ascending positive array to find where the gap count (arr[mid] - mid - 1) first reaches k.

## Medium binary search questions for live coding rounds

Video technical screens and onsite rounds usually step up to medium problems. Here you are expected to write complete code on a shared editor or sketch out pointer invariants on a whiteboard while testing edge cases like duplicates, rotated segments, and monotonic feasibility checks.

1. Search in a rotated sorted array: With unique rotated values, identify which half around mid stays sorted and test whether the target falls inside it.
2. First and last position of a target: Run two boundary searches on a sorted list with duplicates: one shrinking left for the start, one shrinking right for the end.
3. Search a 2D matrix: When each sorted row exceeds the prior row’s tail, map 1D index mid in 0..(m * n - 1) to [mid // n][mid % n].
4. Search in rotated sorted array with duplicates: When nums[left] == nums[mid] == nums[right], step both boundaries inward by one before continuing.
5. Minimum in rotated sorted array: Compare nums[mid] with nums[right] to see which side holds the wrap-around drop onto the smallest item.
6. Find a peak element: Where adjacent values differ, move toward whichever neighbor is larger than nums[mid] because a rising slope ensures a local peak ahead.
7. Count complete tree nodes: Compare left and right spine depths on subtrees, or binary search leaf slots on the bottom row via path bits.
8. Search a 2D matrix sorted independently by row and column: Start at the top-right cell and step left or down to drop one row or column per check.
9. Longest increasing subsequence: Track the smallest tail for each subsequence length in an ordered array, updating entries via lower-bound binary search in O(n log n).
10. H-index in sorted citations: Given ascending citation counts, binary search the earliest index i where citations[i] >= n - i.
11. Random pick with weight: Build prefix sums of weights, draw a uniform integer up to the total, and binary search the first prefix sum reaching it.
12. Heaters: Sort heater coordinates, binary search the nearest left and right heater for every house, and take the maximum minimum distance.
13. Kth smallest element in a sorted matrix: Binary search the value range from top-left to bottom-right while counting matrix values at or below mid.
14. Single element in a sorted array: Pairs start at even indices before the lone item and odd indices after; align mid even and check mid + 1.
15. Find K closest elements: Binary search the start of a length-k window by comparing x - arr[mid] against arr[mid + k] - x.
16. Koko eating bananas: Binary search the smallest hourly speed between 1 and max(piles) that clears every pile within h hours.
17. Online election: Store the leading candidate after each ballot timestamp, then answer any query time by binary searching timestamps.
18. Time-based key-value store: Append chronological (timestamp, value) pairs per key and fetch the newest entry at or before query time via upper-bound search.
19. Capacity to ship packages within D days: Binary search daily ship capacity between max(weights) and sum(weights), counting days needed greedily.

> **Pattern spotlight.** Notice how several medium problems (eating speed, ship capacity, heaters) never search an input array directly. They binary search a monotonic answer range and call a linear helper to verify feasibility.

## Hard binary search questions for onsite depth

Hard binary search questions appear in onsite loops when interviewers want to see how you combine logarithmic partitioning with rolling hashes, dynamic programming, prefix sums, or counting arguments. Expect extra time to reason through invariants before coding.

1. Median of two sorted arrays: Binary search a split index in the shorter array so combined left halves equal half the total and max-left <= min-right.
2. Count of smaller numbers after self: Traverse right to left maintaining a sorted suffix (or merge-sort indices) and binary search how many seen items fall below current.
3. Minimum in rotated sorted array with duplicates: Compare nums[mid] with nums[right], decrementing right by 1 on ties so duplicates cannot mask the pivot.
4. Russian doll envelopes: Sort by width ascending and height descending, then find the longest increasing subsequence of heights with binary search.
5. Largest rectangle sum bounded by K: Fix left and right columns, track running row sums, and query an ordered set via binary search for prior sum >= curr - K.
6. Split array largest sum: Binary search the cap on m contiguous subarray sums between max(nums) and sum(nums), checking feasibility greedily.
7. Smallest good base: For each all-ones representation length m from 60 down to 2, binary search base k so 1 + k + ... + k^(m-1) equals n.
8. Reverse pairs: Count i < j with nums[i] > 2 * nums[j] by pairing merge sort with binary search or a two-pointer scan across sorted halves.
9. Kth smallest number in multiplication table: Binary search value v in 1..m*n and sum min(v // row, n) across rows to count entries <= v.
10. Random pick with blacklist: Remap blacklisted numbers below n - len(blacklist) to valid tail values, or binary search sorted blacklist offsets.
11. Find Kth smallest pair distance: Sort the array, binary search distance d, and count pairs with gap <= d using two pointers.
12. Kth smallest prime fraction: Binary search fraction threshold x in [0, 1], counting fractions p / q below x while tracking the largest one.
13. Preimage size of factorial zeroes function: Trailing zeroes in x! increase monotonically, so binary search where the count equals k (always 0 or 5).
14. Nth magical number: Binary search the smallest integer x where x // a + x // b - x // lcm(a, b) reaches n.
15. Longest duplicate substring: Binary search length L and detect any repeated slice of length L using a rolling hash set.
16. Maximum profit in job scheduling: Sort intervals by end time, compute DP per job, and binary search the latest prior job finishing on or before start.
17. Find in mountain array: Locate the summit via peak search, check the ascending left side, and fall back to searching the descending right side.
18. Online majority element in subarray: Keep sorted index lists per value and binary search range endpoints to test whether frequency meets threshold.

## Four practice problems, in order of difficulty

These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from counting a value with two searches to searching on the answer.

**Problem 1.** The sorted list is 1, 2, 2, 2, 4, 4, 5, 7, 7, 7, 7, 9, 10, 10, 12. How many times does the value 7 occur, found with two binary searches and not a scan? Give an integer.

**Answer:** 4

1. Find the first position holding a value of at least 7 (the left boundary), using a search over the half-open range [lo, hi) with lo = 0 and hi = 15. Move lo to mid + 1 when the value at mid is less than 7, and otherwise move hi to mid.
2. Probes: mid 7 holds 7, so hi = 7. Mid 3 holds 2, so lo = 4. Mid 5 holds 4, so lo = 6. Mid 6 holds 5, so lo = 7. The range is empty and the left boundary is 7.
3. Find the first position holding a value greater than 7 the same way, moving lo to mid + 1 when the value at mid is at most 7. Probes: mid 7 holds 7, so lo = 8. Mid 11 holds 9, so hi = 11. Mid 9 holds 7, so lo = 10. Mid 10 holds 7, so lo = 11. The right boundary is 11.
4. The count is 11 - 7 = 4. Each search takes about log2(15), so 4 probes, and both together cost O(log n) against O(n) for a scan.

**Problem 2.** A sorted list of distinct values was rotated, so it reads 21, 24, 27, 30, 33, 2, 4, 6, 9, 12, 15, 18. At which 0-based index is the value 12? Give an integer.

**Answer:** 9

1. The list is two sorted runs back to back. The smallest value, 2, sits at index 5, so positions 0 to 4 hold 21 to 33 and positions 5 to 11 hold 2 to 18.
2. At every step one half of the range is sorted. Compare the value at lo with the value at mid to find which half that is, then test whether the target lies inside the sorted half.
3. Range 0 to 11, mid 5 holds 2. The right half is sorted, from 2 to 18, and 12 lies in it, so lo = 6. Range 6 to 11, mid 8 holds 9. The right half is sorted from 9 to 18, and 12 lies in it, so lo = 9.
4. Range 9 to 11, mid 10 holds 15. The right half is sorted from 15 to 18 and 12 is not in it, so hi = 9. Range 9 to 9, mid 9 holds 12. The index is 9. Each step halves the range, so the cost is O(log n).

**Problem 3.** There are piles of 7, 12, 3, 20, 9, 15 items. Each hour, a worker picks one pile and clears up to v items from it, never touching two piles in one hour. What is the smallest whole number v that clears all the piles within 11 hours? Give an integer.

**Answer:** 8

1. For a given v, a pile of p items takes ceil(p / v) hours, so the total hours are the sum of ceil(p / v) over the piles. That total never goes up as v goes up, so the answers "fast enough" and "too slow" are split by one boundary, and a binary search can find it.
2. The smallest useful v is 1 and the largest is the biggest pile, 20, so search the range 1 to 20.
3. Test v = 8: the hours are 1 + 2 + 1 + 3 + 2 + 2 = 11, which fits. Test v = 7: 1 + 2 + 1 + 3 + 2 + 3 = 12, which does not.
4. So the smallest v that works is 8. The search tests about log2(20) values, and each test costs O(n).

**Problem 4.** The weights 4, 2, 7, 5, 3, 6, 1, 8 must stay in this order and be split into exactly 3 runs of consecutive weights. The load of a run is the sum of its weights. What is the smallest possible value of the largest load? Give an integer.

**Answer:** 14

1. Ask a yes or no question for a trial limit c: can the weights be packed greedily into at most 3 runs, each with a sum of at most c? Start a new run only when the next weight would push the sum above c.
2. The answer is at least 8, the largest single weight, and at most 36, the total. A larger limit never makes the question harder, so binary search that range for the smallest limit that gets a yes.
3. Limit 14: runs 4, 2, 7 (13), then 5, 3, 6 (14), then 1, 8 (9). That is 3 runs, so 14 works. Limit 13: 4, 2, 7 (13), then 5, 3 (8, and adding 6 gives 14), then 6, 1 (7, and adding 8 gives 15), then 8. That is 4 runs, so 13 fails.
4. The answer is 14. About log2(29) trial limits are tested, each in O(n).

Every answer above is recomputed by a separate program when the site is built, and each is rebuilt by a different route from the written steps. A wrong answer would stop the build. Read [how the problems are checked](https://georgeliinternships.com/methodology.md).

These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.

## A longer ladder of binary search problems

Four worked problems are a start, and a longer list is worth having for the weeks before an interview. The table sorts 18 problem types that interviewers often use for binary search into three sets, with what each set trains. A coaching company that publishes a large question list on this topic sorts its own list by the stage where such questions tend to turn up: simpler ones on a phone screen, harder ones on a video call or onsite round, where you may get more time. We keep that idea and describe each type in our own words.

| Set | Types | Problems to look up | What the set trains |
| --- | --- | --- | --- |
| Easy | 5 | finding a target in a sorted array; the place a value would be inserted; the first bad version; integer square root; whether a value is in a sorted grid | The loop and its boundary on a plain sorted array |
| Medium | 7 | a target in a rotated sorted array; the first and last position of a value; a peak element; the minimum of a rotated array; the k closest values; the slowest eating speed that finishes in time; the least capacity that ships in a number of days | Searching on the answer: a yes or no test that flips once |
| Hard | 6 | the median of two sorted arrays; splitting an array to minimize the largest sum; the k-th smallest pair distance; the k-th smallest value in a multiplication table; a value in a mountain array; the longest repeated substring | A test function that is itself a small algorithm |
*Binary search problem types in three sets, with a count of each*

Do not try to read every solution. New questions appear every season, so the aim is to own the pattern behind a set, not the answer to each item. For each problem, set a timer, write your own attempt with no reference, and only then read a solution. When you get stuck, look at one solution, close it and redo the problem from a blank page the next day. A pile of read solutions teaches far less than a few redone from memory.

Binary search needs an order and quick access by position, so among the basic structures only a sorted array fits. The skill that interviews reward is spotting the hidden sorted thing: a range of possible answers where “is this enough?” flips from no to yes exactly once. Write that test first and the search around it second.

## How to plan your coding interview preparation

Binary search rarely wins an interview loop by itself. Strong preparation pairs search drills with the rest of the core data structures and algorithm families tested across engineering interviews.

### Build breadth through solo practice

Before scheduling mock rounds, make sure you are comfortable implementing and analyzing the foundational topics alongside binary search:

- Arrays and two-pointer scans
- Strings and sliding windows
- Linked lists and pointer manipulation
- Stacks and queues
- Binary trees and traversals
- Graphs (BFS, DFS, and shortest paths)
- Hash maps and sets
- Heaps and priority queues
- Full worked coding interview walkthroughs

To mirror actual whiteboard and shared-document constraints, work through problems on plain paper or a blank text document without autocomplete, syntax coloring, or compiler hints. Writing clean loops by hand exposes off-by-one slips right away.

### Test your explanations with live feedback

Solo drills build pattern recognition, yet eventually you need outside feedback to sharpen how you communicate under a ticking clock. If you know an experienced software engineer who has run technical interviews, trade mock sessions so they can critique your clarifying questions, dry-run tracing, and complexity explanations. Study groups and peer mock swaps with other candidates also help you spot blind spots you miss when coding alone.

## Questions

### How many steps does a binary search take?

About log2(n) probes, because each probe halves the range that is left. A list of 1,000 sorted values needs at most 10 probes to find a value or show it is missing.

### What is the difference between bisect_left and bisect_right?

Both return an insertion point that keeps a sorted list sorted. When the value is already present, bisect_left returns the position before the existing entries and bisect_right returns the position after them.

### Can I use binary search when the list is not sorted?

Yes, when some yes or no test flips from no to yes exactly once as you move along the range. The list does not need to exist: you can search a range of possible answers, as in the speed and capacity problems below.

## How a session helps

A session with George is a place to code a problem aloud and have the reasoning questioned: what the range is, why the test only flips once and what your loop does on two values. You write all the code yourself. Next, read the [data structures checklist](https://georgeliinternships.com/interview-prep/data-structures-checklist.md) and the [coding and complexity practice](https://georgeliinternships.com/interview-prep/coding-and-complexity-practice.md), and use the [coding prep schedule](https://georgeliinternships.com/tools/coding-prep-schedule.md) to put the topics on a calendar. See the [packages page](https://georgeliinternships.com/packages.md) for the sessions, or [book a session](https://georgeliinternships.com/book.md).

## Related

- [Internship interview prep](https://georgeliinternships.com/interview-prep.md)
- [Methodology and sources](https://georgeliinternships.com/methodology.md)
- [Internship role guides](https://georgeliinternships.com/roles.md)
