BeeTool.Dev - Essential Tools for developers

Stories.Tool Tabs VaultPersonal Documents
Super Debugging Context
BeeTool.Dev

Essential tools, knowledge, and playgrounds for developers.

Explore

  • Stories
  • Personal Documents
  • Features
  • Algorithms Playground

Tool Tabs

  • JSON Compare
  • SQL Formatter
  • Text Diff
  • All tools →

Learn

  • Sorting algorithms
  • Searching algorithms
  • Algorithm Race Mode
© 2024 – 2026 BeeTool.DevPrivacy policy
← Algorithms Playground
Searching · Advanced

Interpolation Search

Instead of always probing the middle, estimate where the target should be from its value — O(log log n) on uniformly distributed keys.

AverageO(log log n)StructureSorted arrayNeeds sortedYesComparisonYes
Must remember

Binary search that guesses proportionally to the value gap instead of always picking the middle.

Best O(1) · Avg O(log log n) · Worst O(n) · Space O(1)

Hands on Interactive visualization

Size 24
Target 35
ProbingFoundUnexploredEliminated
0/0Ready — press play
Speed
Step 0 / 0
Comparisons
0
Swaps
0
Reads
0
Writes
0
Elapsed
0.0s
Frames
0
Depth
0 / 0
Aux memory
0 B

Implementation Code

export function interpolationSearch(a: number[], target: number): number {
  let lo = 0;
  let hi = a.length - 1;
  while (lo <= hi && target >= a[lo] && target <= a[hi]) {
    if (a[lo] === a[hi]) {
      // One distinct value left: avoid division by zero.
      return a[lo] === target ? lo : -1;
    }
    // Linear estimate: how far along the value range is the target?
    const pos =
      lo + Math.floor(((target - a[lo]) * (hi - lo)) / (a[hi] - a[lo]));
    if (a[pos] === target) return pos;
    if (a[pos] < target) lo = pos + 1;
    else hi = pos - 1;
  }
  return -1;
}

Big-O Complexity

Best
O(1)
Average
O(log log n)
Worst
O(n)
Space
O(1)

O(log log n) average holds only for uniformly distributed keys; skewed or clustered data (exponential gaps, duplicates) degrades every probe estimate, all the way to O(n).

In production When to use

Uniform numeric keys

Auto-increment IDs, evenly spaced timestamps, sensor readings at fixed intervals — when position is nearly a linear function of value, the interpolated guess lands almost exactly on target.

Time-series lookups

Finding a timestamp in a large append-only log with roughly constant event rate: the proportional guess (elapsed fraction × length) is usually within a few entries of the answer.

Sorted numeric datasets in analytics

Locating percentile boundaries or value ranges in large sorted numeric columns where the distribution is known to be close to uniform after transformation.

Learned-index intuition

Modern learned indexes generalize the same bet: model the key-to-position function (interpolation uses a straight line, learned indexes fit better models) and correct locally around the prediction.

Hybrid searches

Practical systems interpolate for the first probe or two to get close fast, then fall back to binary search for guaranteed convergence — capturing the average-case win without the O(n) tail.

Trade-offs Strengths & weaknesses

  • O(log log n) average on uniform data — 5 probes where binary search needs 30, at n = 10⁹.
  • O(1) extra space, same as binary search.
  • First probe is often within a handful of elements of the target on well-behaved data.
  • The conceptual basis of learned indexes and interpolation-based B-tree node search.
  • Combines cleanly with binary search as a guarded hybrid.
  • Degrades to O(n) on skewed, clustered, or exponentially spaced keys.
  • Requires numeric keys (or an order-preserving numeric mapping) — no plain comparators.
  • The probe formula invites division-by-zero and overflow bugs.
  • Each probe costs arithmetic (multiply, divide) on top of a comparison.
  • Worse worst case than binary search makes it risky as an unguarded default.

Intuition Mental model

Opening the phone book proportionally

Looking up a name starting with W, nobody opens a phone book in the middle — you open it near the back, because you know roughly where W lives in the alphabet. Interpolation search turns that instinct into a formula.

  1. Estimate the fraction: W is about 85% through the alphabet, so open 85% of the way through the book.
  2. Land, read the page, and see how far off you are — usually only a few pages.
  3. Re-estimate proportionally within the smaller range and open again.
  4. Each guess shrinks the range from n toward √n — far faster than halving.
  5. The trick fails on a phone book where half the town is named Smith: proportional guessing needs evenly spread names.

Prep Interview questions

Derive the interpolation probe formula. What assumption makes it work?
Assume value grows linearly with index across [lo, hi]. Then the target's expected offset is (target - a[lo]) / (a[hi] - a[lo]) of the window: pos = lo + (target - a[lo]) * (hi - lo) / (a[hi] - a[lo]).
Why is the average O(log log n), intuitively?
On uniform data, each probe shrinks the expected window from n to about √n — squaring-down instead of halving. Iterating x → √x reaches a constant in log log n steps.
Construct an input that forces interpolation search to O(n).
Exponentially spaced keys like 1, 2, 4, ..., 2^n with a target near the large end: every interpolated probe lands near lo, shaving off one element per step — a disguised linear scan.
How do you make interpolation search safe in production?
Guard the formula (a[hi] == a[lo] means one distinct value: direct compare), clamp pos into [lo, hi], do the arithmetic in a wide type, and cap the iteration count with a binary-search fallback.
How does this relate to learned indexes?
Interpolation fits a single straight line to the key-position function; learned indexes (e.g., the RMI design) fit piecewise or hierarchical models, then binary-search a small error window around the prediction. Same bet, better model.

Watch out Common bugs

Division by zero when a[hi] == a[lo]

A window of equal keys zeroes the denominator. Handle it explicitly: if a[lo] == a[hi], the answer is a single equality check, not a formula.

Overflow in (target - a[lo]) * (hi - lo)

The numerator multiplies a value gap by an index gap — comfortably past 32-bit range on large inputs. Compute in 64-bit (or arbitrary precision) before dividing.

Probe position escaping the window

If the target lies outside [a[lo], a[hi]], the formula extrapolates an index outside [lo, hi] and indexes out of bounds. Check the range first or clamp pos into the window.

No termination guard on skewed data

On adversarial distributions the window shrinks by one per iteration; combined with a subtle boundary bug this becomes an infinite loop. Cap iterations or verify the window strictly shrinks.

One screen Cheat sheet

Binary search that guesses proportionally to the value gap instead of always picking the middle.

Best O(1) · Avg O(log log n) · Worst O(n) · Space O(1)
  • pos = lo + (target - a[lo]) · (hi - lo) / (a[hi] - a[lo]) — a linear estimate of position.
  • O(log log n) average requires uniformly distributed numeric keys.
  • Worst case O(n) on skewed data — always guard or hybridize with binary search.
  • Guard a[hi] == a[lo] (division by zero) and do the multiply in a wide integer type.
  • Each probe shrinks n toward √n on uniform data — squaring-down, not halving.
  • Ancestor of learned indexes: model position from value, correct locally.
Pick whenLarge sorted arrays of uniformly distributed numeric keys — IDs, timestamps, evenly sampled readings.
Avoid whenDistribution is unknown, skewed, or keys aren't numeric — binary search's guaranteed O(log n) is the safer default.

Exponential Search

Hash Lookup