skip to content

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 pageshow

explore

questions

page 2 of 2

Why is exponential search O(log i) in the target's position rather than O(log n)?

level: middleimportance: should knowfreq 36%

basics

~20 s

Both 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.

open as a page

In exponential search over a log of unknown size, why is it safe to search up to an overshooting probe?

level: middleimportance: should knowfreq 28%

basics

~20 s

Because 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.

open as a page

Why is interpolation search O(log log n) expected yet O(n) in the worst case?

level: middleimportance: should knowfreq 34%

basics

~20 s

On 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).

open as a page

In ternary search for a minimum, why is discarding the left third safe when f(m1) is greater than f(m2)?

level: middleimportance: should knowfreq 26%

basics

~20 s

The 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.

open as a page

In a linear search, why is a zero-valued record a bad way to signal 'not found'?

level: middleimportance: should knowfreq 45%

basics

~20 s

A 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'.

open as a page

What property, more general than sortedness, does binary search actually require?

level: middleimportance: should knowfreq 52%

basics

~20 s

Binary 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.

open as a page

In a virtual-1D binary search over a fully sorted grid, why does mid map through the column count?

level: middleimportance: should knowfreq 55%

basics

~20 s

Reading 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.

open as a page

Why does a wrap-point search in a rotated array shrink with hi = mid, not hi = mid - 1?

level: middleimportance: should knowfreq 55%

basics

~20 s

The 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.

open as a page

A leaderboard keeps scores in a sorted array; how do you compute a new score's rank and insert it?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Take 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.

open as a page

In a sorted array, why does counting a value by one binary search plus an outward scan degrade to O(n)?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Walking 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).

open as a page

When would you insist on the iterative form of binary search rather than the recursive one?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Rarely 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.

open as a page

Reviewing a hand-written binary search, which loop invariant convinces you it is correct and terminates?

level: seniorimportance: should knowfreq 42%

basics

~20 s

The 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.

open as a page

A teammate proposes interpolation search over heavily skewed transaction amounts — how do you respond?

level: seniorimportance: should knowfreq 22%

basics

~20 s

Push 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.

open as a page

On an integer domain, what does a plateau where f(m1) equals f(m2) break in ternary search?

level: seniorimportance: should knowfreq 22%

basics

~20 s

A 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.

open as a page

When does a linear scan of 64 contiguous records beat a balanced search tree?

level: seniorimportance: should knowfreq 55%

basics

~20 s

At 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.

open as a page

Can you binary-search event records that are only 'mostly sorted' by timestamp?

level: seniorimportance: should knowfreq 42%

basics

~20 s

No. 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.

open as a page

When does binary searching every row of a row- and column-sorted grid beat the O(m+n) walk?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Per-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.

open as a page

How do duplicate values change the worst case of searching a rotated sorted array?

level: seniorimportance: should knowfreq 46%

basics

~20 s

Duplicates 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).

open as a page

In interpolation search, what breaks when the range's endpoint values a[lo] and a[hi] are equal?

level: middleimportance: nice to knowfreq 14%

basics

~20 s

The 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.

open as a page

Why does a sentinel linear search drop the bounds check, and what does that cost?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

Writing 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.

open as a page

How would you find the kth smallest sum over all pairs of two sample lists without materializing every pair?

level: seniorimportance: nice to knowfreq 35%

basics

~20 s

Binary 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.

open as a page

When does galloping to bracket a range beat one size query plus binary search on a remote sorted log?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Galloping 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.

open as a page

Why does ternary search cost more function evaluations than binary search on the slope sign?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Ternary 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.

open as a page

Is binary searching a tuning parameter still right when each feasibility probe is a noisy 20-minute load test?

level: principalimportance: nice to knowfreq 28%

basics

~20 s

Usually 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.

open as a page

When should a telemetry API promise any local peak in O(log n) instead of the global maximum?

level: principalimportance: nice to knowfreq 22%

basics

~20 s

Promise 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.

open as a page

When is a rotation-aware search not worth shipping, and what would you build instead?

level: principalimportance: nice to knowfreq 26%

basics

~20 s

A 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.

open as a page

showing 31–57 of 57