Data Structures & Algorithms practice
Data Structures & Algorithms · Array Patterns

Binary Search: Practice Questions

100 questions. Try each one yourself before checking the answer.

Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.

Q1Linear SearchEasyMust Do

Write linear search, count the comparisons it makes, and say what it costs.

Q2HalvingEasy

Play the number-guessing game against the computer. Guess the middle every time, and count the guesses.

Q3The Halving ArgumentEasy

How many times can you halve n before nothing is left? Build the table that answers it, and connect it to log2.

Q4The Core LoopEasyMust Do

Write the canonical binary search on a sorted list. This is the version to memorise.

Q5TracingEasy

Print low, mid and high at every step so you can watch the range collapse.

Q6The PreconditionEasyMust Do

Run binary search on an unsorted list. Show that it does not raise — it lies.

Q7Computing the MidpointEasy

Write mid three different ways. Explain which one you would use in C or Java, and why Python does not care.

Q8Reporting AbsenceEasy

Three ways to say "not found": -1, None, and raising. Write all three and say when each is right.

Q9Comparison CountsMedium

Measure linear search against binary search on the same sorted data. Count probes, then time both.

Q10The InvariantEasyMust Do

State the loop invariant of binary search, then assert it on every iteration.

Q11Loop ShapesEasy

What changes if you write while low < high instead of while low <= high? Run both and compare.

Q12Half-Open ShapeEasyMust Do

Write the third shape: the half-open range [low, high) with high = len(values). This is the one the standard library uses.

Q13Mixing ShapesMediumMust Do

Combine the loop condition from one shape with the update from another. Show that it hangs, with a step cap so the program still finishes.

Q14Where It StopsEasy

When the target is absent, where do low and high end up? Show the pattern holds for every possible miss.

Q15Insertion PointEasy

Turn the previous observation into a function: return the index where a value should be inserted to keep the list sorted.

Q16Edge CasesEasy

Test binary search on the inputs that break naive implementations: empty, one item, two items, all-equal.

Q17DuplicatesEasy

With duplicates in the list, which index does plain binary search return? Show that the answer is "an arbitrary one".

Q18First OccurrenceEasyMust Do

Find the index of the first occurrence of a value in a sorted list with duplicates.

Q19Last OccurrenceEasy

Now find the last occurrence. Write it both ways, and note the one-character difference from Q18.

Q20Counting OccurrencesEasy

Count how many times a value appears in a sorted list, in O(log n) — without scanning.

Q21FloorEasy

Find the floor: the largest value in the list that is less than or equal to the target.

Q22CeilingEasy

Find the ceiling: the smallest value greater than or equal to the target. Then note that you already wrote it.

Q23Non-Numeric KeysEasy

Binary search a sorted list of strings, and then a list of dates. Show that the algorithm never mentions numbers.

Q24Searching by KeyMedium

Search a list of records sorted by one field. Write it with an explicit key function.

Q25bisectEasyMust Do

Meet bisect_left and bisect_right. Show that they are exactly the two boundary searches you have already written, and time them against yours.

Q26Insert PositionEasy

Given a sorted list and a target, return the index if it is found, otherwise the index where it would be inserted.

Q27Search RangeMediumMust Do

Given a sorted list with duplicates, return the first and last index of a target as a pair, or [-1, -1].

Q28Counting with bisectEasy

Redo the previous question with bisect, and use it to answer four different counting questions in one line each.

Q29Successor & PredecessorMedium

Find the smallest value strictly greater than the target, and the largest value strictly less. Note how they differ from ceiling and floor.

Q30Closest ElementMedium

Find the value in a sorted list closest to a target. Break ties toward the smaller value.

Q31K ClosestMedium

Find the k values closest to a target in a sorted list, returned in sorted order.

Q32Predicate SearchMediumMust Do

Generalise binary search: given a boolean list that is all False then all True, find the index of the first True. Then show why this generalisation is the whole topic.

Q33First Bad VersionMedium

You have n versions and an is_bad(v) API. Once a version is bad, every later one is bad. Find the first bad version with as few API calls as possible.

Q34Query-Only SearchEasy

You cannot see the data at all — you can only ask "is my guess too high, too low, or correct?". Write the search against that interface.

Q35Integer Square RootMediumMust Do

Compute the integer square root of n — the largest x with x * x <= n — using only integer arithmetic.

Q36Fixed PointMedium

Given a sorted list of distinct integers, find an index i with values[i] == i. Then show why distinctness is required.

Q37Missing ElementMedium

A sorted list holds n distinct numbers drawn from 0..n. Exactly one is missing. Find it in O(log n).

Q38Kth MissingMedium

Given a sorted list of distinct positive integers, find the k-th positive integer that is missing from it.

Q39Peak ElementMediumMust Do

Find a peak in an unsorted list — an element greater than both its neighbours — in O(log n). Explain how binary search can work on unsorted data.

Q40Bitonic ArraysMedium

A bitonic list increases and then decreases. Find its maximum, then search it for an arbitrary value in O(log n).

Q41Rotated MinimumMediumMust Do

A sorted list has been rotated an unknown number of places. Find its minimum in O(log n).

Q42Rotation CountMedium

Find how many places a sorted list has been rotated, and use that to search it with a single ordinary binary search.

Q43Rotated SearchMedium

Search a rotated sorted list for a target in a single binary search pass.

Q44Duplicates in RotatedHard

Add duplicates to the rotated list. Show that the worst case becomes O(n), and write the version that is still correct.

Q452-D as FlatMedium

Search an m x n matrix whose rows are sorted and where each row starts after the previous row ends. Treat it as one flat sorted list.

Q46Staircase SearchMedium

Now the harder matrix: rows sorted left to right and columns sorted top to bottom, but with no relationship between the end of one row and the start of the next. Find a target.

Q47Exponential SearchHard

You can read values[i] but you cannot ask for the length — reading past the end returns a sentinel. Find a target in O(log p), where p is its position.

Q48Interval LookupMedium

Given a list of non-overlapping intervals sorted by start, find which interval contains a query point.

Q49Range CountMedium

Count how many values fall in [lo, hi], and extract them, in O(log n + k).

Q50Choosing the ShapeMediumMust Do

You have met six binary-search shapes. Build the decision table that tells you which one a problem needs, and implement all six behind one interface.

Q51Search on the Answer SpaceMediumMust Do

Here is the idea that turns binary search from a lookup into a technique. Solve a problem with no array in it: find the smallest square-shaped plot of land that fits n trees planted 3 metres apart.

Q52Monotone FeasibilityMediumMust Do

Write the reusable answer-space template, and a checker that proves a feasibility function is monotone before you trust it.

Q53Capacity PlanningMediumMust Do

Packages must ship in order within days days. Find the smallest ship capacity that makes it.

Q54Minimum RateMedium

Koko eats bananas from n piles at k bananas per hour, one pile at a time. Find the smallest k that finishes within h hours.

Q55Minimax PartitionHard

Split a list into m contiguous parts so the largest part-sum is as small as possible. Return that minimum largest sum.

Q56AllocationMedium

n books with page counts must be given to k students in order, each student getting a contiguous block. Minimise the maximum pages any student reads.

Q57Maximise the MinimumHardMust Do

Place k cows in stalls at given positions so the closest pair is as far apart as possible. This is the mirror image of everything so far.

Q58SchedulingMedium

Flowers bloom on given days. You need m bouquets of k adjacent flowers each. Find the earliest day you can make them.

Q59Threshold SearchMedium

Find the smallest divisor such that the sum of every value divided by it (rounded up) stays under a threshold.

Q60Count-Based SearchHard

Find the k-th smallest value in a matrix whose rows and columns are both sorted, without flattening it.

Q61Median of Two ArraysHardMust Do

Find the median of two sorted arrays in O(log(min(m, n))) — without merging them.

Q62Kth of Two ArraysHard

Generalise: find the k-th smallest element of two sorted arrays.

Q63Real-Valued SearchMedium

Binary search over real numbers: compute a square root to six decimal places. Then explain why low < high no longer terminates.

Q64Fixed IterationsHard

Compute the n-th root of a positive number with a fixed iteration count, and handle the case where the true root lies outside your first bracket.

Q65Real-Valued MinimaxHard

Gas stations sit at given positions. Add k new stations anywhere to minimise the largest gap between adjacent stations. Answer to within 1e-6.

Q66When It Pays OffMedium

Sorting costs O(n log n) and each search then costs O(log n). Measure the crossover: at how many queries does sort-then-search beat repeated linear scanning?

Q67Searching by Key at ScaleMedium

Search a large list of records by a sorted field, three ways, and measure which is fastest.

Q68Time-Based LookupMedium

Build a store where set(key, value, timestamp) records a value and get(key, timestamp) returns the value in effect at that moment.

Q69The Last TrueHard

Write the mirror template properly: find the largest value for which a condition holds. Then show the three ways people get it wrong.

Q70The TemplateMedium

Write the answer-space reference card: one function, one checklist, and five worked problems solved by filling in a single feasibility test.

Q71Infinite LoopsHardMust Do

Catalogue every way a binary search can fail to terminate, and build a harness that detects each one automatically.

Q72Midpoint BiasHard

(low + high) // 2 rounds down. Show exactly when that breaks a search, and write the rounding-up midpoint that fixes it.

Q73Integer OverflowHard

Simulate 32-bit arithmetic and reproduce the binary-search overflow bug that shipped in the JDK. Then find the other places in this topic where overflow would bite outside Python.

Q74Silent Wrong AnswersHardMust Do

Binary search on unsorted data does not raise. Build the defences: a debug assertion, a cheap sampled check, and a strategy for the case that is worst of all — nearly sorted data.

Q75Wrong Sort OrderHard

The list is sorted — just not the way the search compares. Four ways this happens, and how to make the mismatch impossible.

Q76Off-by-OneHardMust Do

Here are four implementations of "first occurrence". Exactly one is correct. Find the bugs by differential testing rather than by reading.

Q77Choosing the Wrong bisectHard

bisect_left and bisect_right differ only when the target is present. Find four places where that difference is the whole answer.

Q78Broken MonotonicityHard

Run an answer-space search against a feasibility function that is not monotone. Show that it returns a real-looking number, and build the check that catches it.

Q79Float TerminationHard

Write a float binary search that never terminates, and three that do. Explain what goes wrong at the limits of floating point.

Q80Comparison FailuresHard

The search is correct and the list is sorted, but the comparison itself misbehaves. None, mixed types, NaN, and a broken __lt__.

Q81Mutation During SearchHard

Mutate the list while a search is in progress, and let a cached key list go stale. Two bugs that only appear under concurrency or long-lived state.

Q82Accidental QuadraticHard

Two ways to make binary search slower than a linear scan: insort in a loop, and re-sorting per query. Measure both.

Q83Why It Needs O(1) IndexingHard

Binary search assumes values[i] is free. Simulate a container where it is not, and show the algorithm becomes worse than a linear scan.

Q84Misleading TestsHard

Here is a binary search that passes a thorough-looking test suite and is wrong. Find the input class the suite never covers, and write the test that would have caught it.

Q85Code ReviewHard

Five binary searches from a real code review. Find every bug, say what it costs, and fix each one.

Q86Mini-Project · Sorted IndexMini-ProjectMust Do

Build a SortedIndex class: a collection that stays sorted and answers every ordered query you have met in this topic. Include the costs in the docstrings, honestly.

Q87Mini-Project · Version BisectMini-Project

Build git bisect: find the commit that introduced a bug, given a list of commits and a test. Handle commits that cannot be tested.

Q88Mini-Project · AutocompleteMini-Project

Build prefix autocomplete over a sorted word list using two binary searches. Rank the results, and measure it against scanning.

Q89Mini-Project · LeaderboardMini-Project

Build a leaderboard: submit scores, then answer rank, percentile, top-k, and "players near me" queries.

Q90Mini-Project · Rate TunerMini-ProjectMust Do

Find the highest request rate a service can sustain while keeping its 99th-percentile latency under a limit. This is answer-space search against a simulation.

Q91Mini-Project · Time-Series StoreMini-Project

Build a time-series store with as-of lookups, range extraction, and bucketed downsampling — all on sorted timestamps.

Q92Mini-Project · Shard PlannerMini-Project

Split a sorted key space across k servers so the busiest server is as lightly loaded as possible. Then verify the plan.

Q93Mini-Project · Grade BandsMini-Project

Build a configurable band classifier — grades, tax brackets, shipping tiers — and test the boundaries properly.

Q94Mini-Project · Query PlannerMini-Project

Write a planner that chooses between scanning, sorting-then-searching, and hashing — from statistics about the workload. Then check its decisions by measurement.

Q95Mini-Project · Search Test KitMini-Project

Build a reusable harness that fuzzes any binary search implementation, catches hangs, and shrinks a failure to its smallest reproducing input.

Q96Explaining Binary SearchInterview

Explain binary search to three audiences: a twelve-year-old, a working developer who has never needed it, and an interviewer who wants the proof. Same idea, three depths.

Q97DiagnosingInterview

"Our product search got slow after we added a million items, and sometimes it returns nothing for products we know exist." Work the diagnosis.

Q98Design Under ConstraintInterview

Design a lookup that answers "what is the value at time t" for a billion readings, using at most 25 probes and O(1) extra memory, where the data lives on disk and does not fit in RAM.

Q99Mock InterviewInterview

A full transcript. "Find a target in a rotated sorted array." Watch the parts that earn marks — and the parts that lose them.

Q100CapstoneInterviewMust Do

Build an ordered analytics engine that uses every technique in this topic: boundary searches for the query surface, answer-space search for planning, and a verification suite that proves the whole thing.

Stuck? Solve it with a mentor.

Your first 1-on-1 session is free.

Book my free session