Searching & Binary Search
Covers how to find things fast: linear search as the baseline, binary search as the interview canon, and the family of variants built on the same halving idea. Interviewers lean on this topic because binary search is short enough to probe precisely — a single off-by-one or a wrong boundary choice reveals whether you truly reason about invariants or just memorized a template.
part ofData structures & algorithmsoverview, primer and where to startread it →on this pageshowhide
explore
- Baseline Search & Preconditions8 questions
- Linear Search4 questions
- The Sorted-Input Precondition4 questions
- Core Binary Search8 questions
- Mechanics & Complexity4 questions
- Pitfalls & Loop Invariants4 questions
- Boundary Variants8 questions
- First & Last Occurrence4 questions
- Lower/Upper Bound & Insertion Point4 questions
- Binary Search on the Answer8 questions
- Monotonic Predicate Framing4 questions
- Classic Answer-Space Formulations4 questions
- Rotated & Modified Inputs13 questions
- Rotated Sorted Arrays5 questions
- Searching Sorted 2D Matrices4 questions
- Peak Finding & Bitonic Arrays4 questions
- Exotic Search Variants12 questions
- Exponential Search4 questions
- Interpolation Search4 questions
- Ternary Search & Unimodal Functions4 questions
- Computer Scienceskillanchors this topic
- Data Structures & Algorithmsskillanchors this topic
- AI & Data Scientistrole
- AI Engineerrole
- AI Red Teamingrole
- Android Developerrole
- Backend Developerrole
- Blockchain Developerrole
- Cyber Security Expertrole
- Data Analystrole
- Data Engineerrole
- DevOps / SRE Engineerrole
- DevSecOps Engineerrole
- Forward Deployed Engineerrole
- Frontend Developerrole
- Full Stack Developerrole
- Game Developerrole
- Java Backend Developerrole
- Java SDETrole
- Kotlin Backend Developerrole
- MLOps Engineerrole
- Machine Learning Engineerrole
- Network Engineerrole
- PostgreSQL DBArole
- QA Engineerrole
- Software Architectrole
- iOS Developerrole
questions
page 2 of 2Why is exponential search O(log i) in the target's position rather than O(log n)?
basics
~20 sBoth phases are bounded by where the answer sits, not by how much data exists: doubling stops at the first power of two past position i, and the binary search then covers an interval no wider than i.
In exponential search over a log of unknown size, why is it safe to search up to an overshooting probe?
basics
~20 sBecause reads past the last entry answer the search predicate as satisfied, the predicate stays false-then-true across the whole bracket, so a first-true binary search converges even when the upper index lies beyond the data.
Why is interpolation search O(log log n) expected yet O(n) in the worst case?
basics
~20 sOn near-uniformly spaced keys each interpolated probe narrows the remaining range from about n to about the square root of n, which compounds to O(log log n) expected probes. When spacing is skewed, the probe creeps toward one end an element at a time, giving O(n).
In ternary search for a minimum, why is discarding the left third safe when f(m1) is greater than f(m2)?
basics
~20 sThe alternative is impossible: if the minimum sat at or left of m1, the curve would rise from m1 to m2, forcing f(m1) below f(m2) — the opposite of what was measured. So the minimum lies strictly right of m1.
In a linear search, why is a zero-valued record a bad way to signal 'not found'?
basics
~20 sA zero-valued record conflates three different outcomes: the entry is missing, the collection was empty, and the entry exists but its value happens to be zero or disabled. Callers cannot tell them apart, so a failed load silently reads as 'everything off'.
What property, more general than sortedness, does binary search actually require?
basics
~20 sBinary search requires a monotone predicate over the search range: false everywhere below some boundary and true everywhere above it. A sorted collection is just the case where "is this element at least the target" happens to be monotone.
In a virtual-1D binary search over a fully sorted grid, why does mid map through the column count?
basics
~20 sReading order packs cols entries into every row, so flat position mid sits at row mid / cols, column mid % cols. Dividing by the row count instead coincides only on square grids, which is why that bug survives square tests.
How do you search a bitonic array — samples that rise then fall — for a target in O(log n)?
basics
~20 sBitonic search runs in two stages: a slope-comparison binary search locates the single apex, then two ordinary binary searches cover the rising side ascending and the falling side descending. Three logarithmic passes in sequence are still O(log n).
Why does a wrap-point search in a rotated array shrink with hi = mid, not hi = mid - 1?
basics
~20 sThe midpoint itself may be the wrap point: when its value is not greater than the value at the high end, it stays a candidate for the smallest element, so discarding it can lose the answer.
A leaderboard keeps scores in a sorted array; how do you compute a new score's rank and insert it?
basics
~20 sTake the upper bound of the score; n minus that index counts the players who strictly beat it, so the rank is one more. That index is also the insertion position, but the insert costs O(n) moves.
In a sorted array, why does counting a value by one binary search plus an outward scan degrade to O(n)?
basics
~20 sWalking outward from a match touches one element per duplicate, so counting costs O(log n + k) for a run of k equal keys, and k grows with the very skew that motivated the query. Two boundary searches stay O(log n).
When would you insist on the iterative form of binary search rather than the recursive one?
basics
~20 sRarely on stack-depth grounds: recursion nests only floor(log2 n) + 1 deep, about 30 frames at a billion entries. Insist on the loop when the stack is genuinely tiny or already deep, or when per-call overhead matters in a hot path.
Reviewing a hand-written binary search, which loop invariant convinces you it is correct and terminates?
basics
~20 sThe invariant is that if the sought value is present, its position lies inside the current range. Check that the initial bounds establish it, that each branch discards only ruled-out positions, and that an empty range at exit proves absence.
A teammate proposes interpolation search over heavily skewed transaction amounts — how do you respond?
basics
~20 sPush back: the O(log log n) figure is an expectation conditional on near-uniform spacing, and transaction amounts are heavy-tailed, so probes creep from one end and the search degrades toward O(n). Adopt it only where spacing is guaranteed by construction, not hoped for.
On an integer domain, what does a plateau where f(m1) equals f(m2) break in ternary search?
basics
~20 sA plateau breaks the elimination argument. Equal probe values pin the optimum between them only under strict unimodality; on a flat run it is uninformative: the plateau can extend past both probes, so the discarded third may hold the optimum.
When does a linear scan of 64 contiguous records beat a balanced search tree?
basics
~20 sAt sixty-four elements the asymptotics barely apply: a scan of fixed-size contiguous records is a tight, predictable loop over cheap comparisons, while a tree pays pointer chasing, per-node overhead, and build and maintenance cost that so few elements never repay.
Can you binary-search event records that are only 'mostly sorted' by timestamp?
basics
~20 sNo. The precondition is all-or-nothing: one inversion can send a probe down the half that does not contain the target, and the search returns a wrong answer with no error. Restore or enforce the ordering first, or scan.
When does binary searching every row of a row- and column-sorted grid beat the O(m+n) walk?
basics
~20 sPer-row binary search costs O(m log n) and beats the O(m+n) corner walk only on short, wide grids — few rows, many columns — because the row count multiplies the logarithm. On tall or square grids the walk wins outright.
How do duplicate values change the worst case of searching a rotated sorted array?
basics
~20 sDuplicates can make the midpoint tie with both endpoints, leaving the ordered side unidentifiable. The only safe move is then to shrink one bound by a single position, so the worst case rises from O(log n) to O(n).
In interpolation search, what breaks when the range's endpoint values a[lo] and a[hi] are equal?
basics
~20 sThe probe formula divides by a[hi] - a[lo], so equal endpoint values make the denominator zero and the probe computation fault or produce nonsense. It happens on any plateau of duplicates and, in the textbook loop, on every single-element range too.
Why does a sentinel linear search drop the bounds check, and what does that cost?
basics
~20 sWriting the target into a spare slot just past the last live record guarantees the loop terminates on a match, so each iteration tests equality only, never the end of the buffer. It costs a writable spare slot, a restore, and a check that the hit was not the sentinel.
How would you find the kth smallest sum over all pairs of two sample lists without materializing every pair?
basics
~20 sBinary search the range of possible sum values rather than the pairs. With both lists sorted, count in one linear sweep how many pairs sum to at most a candidate x, then take the smallest x whose count reaches k.
When does galloping to bracket a range beat one size query plus binary search on a remote sorted log?
basics
~20 sGalloping wins when the size is unavailable, expensive or stale, or when targets cluster near the head, since its cost tracks the answer's position. A cheap, exact size wins for uniformly placed targets: one plain search halves the probes.
Why does ternary search cost more function evaluations than binary search on the slope sign?
basics
~20 sTernary search keeps two-thirds of the interval per step and spends two probes doing it — about 3.4 evaluations per halving. Bisecting on the slope's sign halves the interval for one or two. Same complexity class, worse constant.
Is binary searching a tuning parameter still right when each feasibility probe is a noisy 20-minute load test?
basics
~20 sUsually not in its textbook form: eleven serial twenty-minute probes cost most of a day, and one noisy probe near the flip point permanently discards the correct half. Probe in parallel batches and ship with margin.
When should a telemetry API promise any local peak in O(log n) instead of the global maximum?
basics
~20 sPromise a local peak only when consumers genuinely need a point where the climb stops and the input is guaranteed single-humped, so the two answers coincide. Promise the global maximum whenever results are compared, alerted on or reported.
When is a rotation-aware search not worth shipping, and what would you build instead?
basics
~20 sA rotation-aware search is not worth shipping when the range is small, queried rarely, or written by code you control. Recording the wrap position at write time, or normalising once on read, removes the rotation and a class of boundary bugs.
showing 31–57 of 57