Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Exponential & Interpolation Search

Searching unbounded lists and uniform data, plus fractional cascading across many lists.

Binary search treats every sorted array alike, and that is its weakness as much as its strength. If the answer sits near the front, galloping finds it in O(log⁡i)O(\log i) probes, even in a list with no known end. If the keys are spread evenly, guessing where a key should be takes about log⁡2log⁡2n\log_2 \log_2 n probes: four or five for a million keys instead of twenty. And if you must search many lists for the same key, you can pay for one binary search instead of many.

What you’ll learn

  • Analyze exponential (galloping) search, 2⌊log⁡2i⌋+O(1)2\lfloor \log_2 i \rfloor + O(1) probes for an answer at position ii, and use it for unbounded search, uneven merges and Timsort's galloping mode.
  • Prove with Kraft's inequality that every unbounded search algorithm needs more than log⁡2N+log⁡2log⁡2N\log_2 N + \log_2 \log_2 N questions for infinitely many NN, by viewing search strategies as prefix codes.
  • Explain why interpolation search makes about log⁡2log⁡2n\log_2 \log_2 n expected probes on uniformly random keys, and construct inputs that force Θ(n)\Theta(n) probes.
  • Build a fractional-cascading structure that searches kk sorted lists of total size nn in O(log⁡n+k)O(\log n + k) time and O(n)O(n) space, and prove both bounds.

Galloping: pay for the distance, not the length

Binary search over [0,n)[0, n) spends about log⁡2n\log_2 n probes even when the answer is at index 3. Exponential search (also called galloping or doubling search) first probes indices 1,2,4,8,…1, 2, 4, 8, \dots until it overshoots, then binary searches the last gap. If the answer is at index ii, the doubling phase makes about log⁡2i\log_2 i probes and the binary search about log⁡2i\log_2 i more: O(log⁡i)O(\log i), however long the array is, and without knowing nn at all.

python
def gallop(a, x):
    """First index i with a[i] >= x, in O(log i) probes; len(a) if there is none."""
    n = len(a)
    if n == 0 or a[0] >= x:
        return 0
    bound = 1
    while bound < n and a[bound] < x:   # invariant: a[bound // 2] < x
        bound *= 2
    lo, hi = bound // 2 + 1, min(bound, n)   # the answer lies in [lo, hi]
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

Tested against bisect_left. Counting probes, it never makes more than 2⌊log⁡2i⌋+32\lfloor \log_2 i \rfloor + 3 for an answer at index i≥1i \ge 1.

Check your understanding

A sorted array has 10910^9 elements, and the lower bound of xx is index 100. About how many probes do gallop and plain binary search make?

  1. About 7 and 30
  2. About 15 and 30
  3. About 30 and 30
  4. About 100 and 30
Show the answer

B. About 15 and 30

After checking a[0]a[0], doubling probes indices 1,2,4,…,1281, 2, 4, \dots, 128 (8 probes) and stops at 128. The binary search over the candidates from 65 to 128 adds 6: 15 probes in all, 2⌊log⁡2100⌋+32\lfloor \log_2 100 \rfloor + 3. Binary search over 10910^9 elements needs ⌊log⁡2109⌋+1=30\lfloor \log_2 10^9 \rfloor + 1 = 30.

Galloping pays off whenever answers sit close to a known position:

  • Merging uneven lists. To merge mm keys into n≫mn \gg m, gallop through the long list for each short-list key instead of comparing one by one. Hwang and Lin (1972) gave a merge with about mlog⁡2(n/m)+O(m)m \log_2(n/m) + O(m) comparisons, close to the information-theoretic minimum log⁡2(m+nm)\log_2 \binom{m+n}{m}.
  • Timsort's galloping mode. When one run keeps winning comparisons during a merge, Timsort switches to exponential search, so runs that barely interleave merge with far fewer than m+nm + n comparisons.
  • Finger search. With a finger on position ff of a sorted array, or in a suitable search tree, a key at position ii is found in O(log⁡∣i−f∣)O(\log \abs{i - f}).

Near the end of the array, galloping costs about 2log⁡2n2 \log_2 n, twice binary search's price: it wins only when ii is well below n\sqrt n.

Unbounded search and prefix codes

Strip galloping down to its core and you get the unbounded search problem of Bentley and Yao (1976): identify an unknown positive integer NN by asking questions "is N<mN < m?". The questions you ask, and the order of the answers, turn out to be the same thing as a code for the integers, and that view gives both the best algorithms and a lower bound.

DerivationSearch strategies are prefix codes
  1. c1(N)=2⌊log⁡2N⌋+1c_1(N) = 2 \lfloor \log_2 N \rfloor + 1

    Doubling. Ask "N<2N < 2?", "N<4N < 4?", "N<8N < 8?", …. The first yes, after ⌊log⁡2N⌋+1\lfloor \log_2 N \rfloor + 1 questions, pins NN to [2j,2j+1)[2^j, 2^{j+1}) with j=⌊log⁡2N⌋j = \lfloor \log_2 N \rfloor, and binary search over those 2j2^j candidates takes jj more:

  2. search strategy  ⟷  prefix code,c(N)=questions asked\text{search strategy} \;\longleftrightarrow\; \text{prefix code}, \qquad c(N) = \text{questions asked}

    Codes. Write the answers as bits, 1 for yes. A deterministic algorithm stops as soon as it knows NN, so no algorithm's answer sequence for one NN is a prefix of its sequence for another: every unbounded search algorithm is a prefix-free code for the positive integers, with codeword length c(N)c(N). Doubling is exactly Elias's gamma code.

  3. c2(N)=⌊log⁡2N⌋+2⌊log⁡2(⌊log⁡2N⌋+1)⌋+1=log⁡2N+2log⁡2log⁡2N+O(1)c_2(N) = \lfloor \log_2 N \rfloor + 2 \lfloor \log_2 (\lfloor \log_2 N \rfloor + 1) \rfloor + 1 = \log_2 N + 2 \log_2 \log_2 N + O(1)

    Better strategies. Find ⌊log⁡2N⌋+1\lfloor \log_2 N \rfloor + 1 itself by doubling, then binary search within [2j,2j+1)[2^j, 2^{j+1}): that is Elias's delta code. Recursing further gives Bentley and Yao's family of algorithms, approaching log⁡2N+log⁡2log⁡2N+log⁡2log⁡2log⁡2N+⋯\log_2 N + \log_2 \log_2 N + \log_2 \log_2 \log_2 N + \cdots up to lower-order terms.

  4. ∑N≥12−c(N)≤1but∑N≥N02−(log⁡2N+log⁡2log⁡2N)=∑N≥N01Nlog⁡2N=∞\sum_{N \ge 1} 2^{-c(N)} \le 1 \qquad\text{but}\qquad \sum_{N \ge N_0} 2^{-(\log_2 N + \log_2 \log_2 N)} = \sum_{N \ge N_0} \frac{1}{N \log_2 N} = \infty

    Lower bound. Prefix codes obey Kraft's inequality. If an algorithm had c(N)≤log⁡2N+log⁡2log⁡2Nc(N) \le \log_2 N + \log_2 \log_2 N for all large NN, its sum would include the tail of a divergent series:

  5. c(N)>log⁡2N+log⁡2log⁡2Nfor infinitely many Nc(N) > \log_2 N + \log_2 \log_2 N \quad \text{for infinitely many } N

    So every unbounded search algorithm asks more than log⁡2N+log⁡2log⁡2N\log_2 N + \log_2 \log_2 N questions for infinitely many NN, and the same argument works with each further iterated logarithm. Bentley and Yao derived a lower bound of this kind showing that their algorithms are within lower-order terms of optimal, hence their title, An almost optimal algorithm for unbounded searching.

Interpolation search: guess where the key should be

Looking up "Mozart" in a printed phone book, you open it near the middle-back, not at the exact middle: you interpolate. If the keys are numbers spread evenly between a[lo]a[lo] and a[hi]a[hi], the key xx should sit about here:

pos=lo+⌊(x−a[lo]) (hi−lo)a[hi]−a[lo]⌋pos = lo + \left\lfloor \frac{(x - a[lo])\,(hi - lo)}{a[hi] - a[lo]} \right\rfloor
Interpolation search probes this position instead of the midpoint, then continues on the side that must contain xx.
DerivationWhy one probe takes n to about √n (a sketch)
  1. rank of x∼Bin(m,p),Var⁡=m p (1−p)≤12m\text{rank of } x \sim \mathrm{Bin}(m, p), \qquad \sqrt{\Var} = \sqrt{m\,p\,(1 - p)} \le \tfrac12 \sqrt m

    Fresh randomness. Given the current range, its mm inner keys are again independent and uniform between the two end values. The number of them below xx is binomial with mean mpmp, where pp is the relative position of xx in the interval, and the probe aims at that mean:

  2. T(m)≤T(O(m))+O(1)T(m) \le T\big(O(\sqrt m)\big) + O(1)

    Square-root shrinking. So the probe typically lands within a few multiples of m\sqrt m of the target. The full analyses turn this into an expected recurrence in which one probe cuts the range from mm candidates to O(m)O(\sqrt m):

  3. j≈log⁡2log⁡2n(n=106: log⁡2log⁡2n≈4.3)j \approx \log_2 \log_2 n \qquad (n = 10^6:\ \log_2 \log_2 n \approx 4.3)

    Doubly logarithmic. Each probe roughly halves log⁡m\log m, so after jj probes about 2−jlog⁡2n2^{-j} \log_2 n remains, and a constant range is reached after

python
def interpolation_search(a, x):
    """Index of x in the sorted list a of distinct integers, or -1."""
    lo, hi = 0, len(a) - 1
    while lo <= hi and a[lo] <= x <= a[hi]:
        if a[hi] == a[lo]:
            pos = lo
        else:                        # integer arithmetic keeps the guess exact
            pos = lo + (x - a[lo]) * (hi - lo) // (a[hi] - a[lo])
        if a[pos] == x:
            return pos
        if a[pos] < x:
            lo = pos + 1
        else:
            hi = pos - 1
    return -1

With keys drawn uniformly from [0,1012)[0, 10^{12}), a test of this code averaged about 3.3 probes for n=103n = 10^3 and 4.3 for n=106n = 10^6, matching log⁡2log⁡2n\log_2 \log_2 n; binary search needs about 10 and 20.

Learned indexes push the idea further. Kraska and colleagues (2018) observed that predicting where a key sits in a sorted array is learning the cumulative distribution function of the keys, and replaced the top levels of B-trees with small models whose bounded prediction error a short local search then fixes. Interpolation search is the simplest such model: a straight line through the two ends of the range.

Fractional cascading: one search for k lists

You hold kk sorted lists L1,…,LkL_1, \dots, L_k with nn keys in total, and each query asks where a key xx belongs in every list. Separate binary searches cost O(klog⁡n)O(k \log n). Fractional cascading (Chazelle & Guibas, 1986) answers in O(log⁡n+k)O(\log n + k) after linear-time preprocessing: the first search does the real work, and each further list costs O(1)O(1). The trick is to copy a sample of each list into the one before it, so that a position found in one list points almost exactly at the position in the next.

text
BUILD(L1, ..., Lk):                      # every list ends with the sentinel +inf
    M[k] <- Lk
    for i <- k-1 down to 1:
        M[i] <- MERGE(Li, every second key of M[i+1])
        for each position p of M[i]:     # filled in during the merge, in linear time
            own[i][p]    <- position in Li of the first key >= M[i][p]
            bridge[i][p] <- position in M[i+1] of the first key >= M[i][p]
    own[k][p] <- p for every p           # M[k] is Lk itself

QUERY(x):                                # where x belongs in each list
    p <- LOWER-BOUND(M[1], x)              # the only binary search
    for i <- 1 to k:
        answer[i] <- own[i][p]
        if i < k:
            q <- bridge[i][p]
            if q > 0 and M[i+1][q-1] >= x: q <- q - 1   # at most one step back
            p <- q
    return answer

Each augmented list MiM_i is LiL_i plus every second key of Mi+1M_{i+1}. A Python version of this structure, tested on random lists against separate binary searches, never needed more than one step back.

DerivationProof of the bounds
  1. ∑i∣Mi∣  ≤  ∑j∣Lj∣(1+12+14+⋯ )  ≤  2n\sum_i \abs{M_i} \;\le\; \sum_j \abs{L_j}\left(1 + \tfrac12 + \tfrac14 + \cdots\right) \;\le\; 2n

    Space. Each augmented list holds its own keys plus half of the next one: ∣Mi∣≤∣Li∣+∣Mi+1∣/2\abs{M_i} \le \abs{L_i} + \abs{M_{i+1}}/2. Unrolling, the keys of LjL_j contribute at most ∣Lj∣\abs{L_j} to MjM_j, ∣Lj∣/2\abs{L_j}/2 to Mj−1M_{j-1}, ∣Lj∣/4\abs{L_j}/4 to Mj−2M_{j-2}, and so on:

  2. q−q∗≤1q - q^* \le 1

    One step back. Let pp be the first position of MiM_i with key ≥x\ge x, so owni[p]own_i[p] is correct: Li⊆MiL_i \subseteq M_i has no key in [x,Mi[p])[x, M_i[p]). The bridge qq is the first position of Mi+1M_{i+1} with key ≥Mi[p]\ge M_i[p], and the true position q∗q^*, the first with key ≥x\ge x, satisfies q∗≤qq^* \le q. The keys at positions q∗,…,q−1q^*, \dots, q - 1 all lie in [x,Mi[p])[x, M_i[p]). Of any two consecutive positions of Mi+1M_{i+1}, one was copied into MiM_i, and a copied key in [x,Mi[p])[x, M_i[p]) would contradict the choice of pp. So

  3. O(log⁡2n)+k⋅O(1)=O(log⁡n+k)O(\log 2n) + k \cdot O(1) = O(\log n + k)

    Query time. One binary search in M1M_1, which has at most 2n2n keys, then constant work per list:

Check your understanding

Suppose each MiM_i copies every fourth key of Mi+1M_{i+1} instead of every second. What happens to the bounds?

  1. Space grows to about 4n4n, with still at most one step back
  2. Queries cost O(klog⁡n)O(k \log n) again
  3. Space shrinks to about 43n\tfrac43 n, and a query may step back up to three positions per list
  4. The query becomes incorrect
Show the answer

C. Space shrinks to about 43n\tfrac43 n, and a query may step back up to three positions per list

The geometric series becomes 1+14+116+⋯=431 + \tfrac14 + \tfrac1{16} + \cdots = \tfrac43. Among any four consecutive positions of Mi+1M_{i+1} one is copied, so at most three keys can lie between the bridge and the true position. Any constant sampling rate gives O(n)O(n) space and O(log⁡n+k)O(\log n + k) time; the rate trades one constant against the other.

Chazelle and Guibas proved the general version, in which the lists hang on the nodes of any graph of bounded degree and a query walks a path of kk nodes. Applications include layered range trees, which answer 2-D orthogonal range queries in O(log⁡n+output)O(\log n + \text{output}) instead of O(log⁡2n+output)O(\log^2 n + \text{output}), planar point location, and, in contests, the merge-sort tree, whose O(log⁡2n)O(\log^2 n) queries drop to O(log⁡n)O(\log n) with cascading.

Key takeaways

  • Galloping finds an answer at position ii with at most 2⌊log⁡2i⌋+32\lfloor \log_2 i \rfloor + 3 probes and needs no length; it powers uneven merges, Timsort's galloping mode and finger search, and loses to binary search only near the end of an array.
  • Unbounded search strategies are prefix codes for the integers: doubling is Elias's gamma code, and Kraft's inequality rules out log⁡2N+log⁡2log⁡2N\log_2 N + \log_2 \log_2 N questions for all large NN.
  • Interpolation search averages about log⁡2log⁡2n\log_2 \log_2 n probes on uniformly random keys (about 4.3 for a million) but needs Θ(n)\Theta(n) in the worst case; robust versions mix in binary steps, and learned indexes generalize the guess.
  • Fractional cascading copies every second key of each list into the previous one, so one binary search plus O(1)O(1) work per list answers a query on kk lists: O(log⁡n+k)O(\log n + k) time in O(n)O(n) space.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

On an array of length nn, when does exponential search beat plain binary search by more than a constant factor?

  1. When the answer's index ii is small, so that log⁡i\log i is far smaller than log⁡n\log n
  2. Always: it never makes more probes than binary search
  3. When the keys are uniformly distributed
  4. When the array contains duplicates
Show the answer

A. When the answer's index ii is small, so that log⁡i\log i is far smaller than log⁡n\log n

Galloping costs about 2log⁡2i2 \log_2 i probes against log⁡2n\log_2 n for binary search, so it wins big when ii is tiny compared with nn and loses by up to a factor of 2 when the answer is near the end. Its other advantage is that it never needs nn.

Question 2

Which statement about unbounded search (identify an unknown positive integer NN with questions "is N<mN < m?") is true?

  1. Some algorithm asks only log⁡2N+O(1)\log_2 N + O(1) questions for every NN
  2. Doubling search is optimal up to an additive constant
  3. No algorithm asks at most log⁡2N+log⁡2log⁡2N\log_2 N + \log_2 \log_2 N questions for all large NN, because answer sequences form a prefix code and ∑1/(Nlog⁡N)\sum 1/(N \log N) diverges
  4. The problem cannot be solved without an upper bound on NN
Show the answer

C. No algorithm asks at most log⁡2N+log⁡2log⁡2N\log_2 N + \log_2 \log_2 N questions for all large NN, because answer sequences form a prefix code and ∑1/(Nlog⁡N)\sum 1/(N \log N) diverges

Answer sequences of a deterministic search form a prefix-free code, so ∑N2−c(N)≤1\sum_N 2^{-c(N)} \le 1. Lengths c(N)≤log⁡2N+log⁡2log⁡2Nc(N) \le \log_2 N + \log_2 \log_2 N for all large NN would make that sum diverge.

Question 3

Interpolation search runs on the 1,000 sorted keys 1,2,…,999,1091, 2, \dots, 999, 10^9. About how many probes does a search for 999 make?

  1. About 3, since log⁡2log⁡21000≈3.3\log_2 \log_2 1000 \approx 3.3
  2. About 10, like binary search
  3. About 999: every guess lands at the low end of the range and gains a single position
  4. 1: the formula computes the exact position
Show the answer

C. About 999: every guess lands at the low end of the range and gains a single position

The giant last key makes the formula place 999 near the start of the range at every step, so each probe removes one key: 999 probes, as running the code confirms. The log⁡2log⁡2n\log_2 \log_2 n bound is an average over uniformly random keys, not a worst-case guarantee.

Question 4

With fractional cascading over kk sorted lists holding nn keys in total, which bounds hold?

  1. O(klog⁡n)O(k \log n) per query, O(n)O(n) space
  2. O(log⁡n+k)O(\log n + k) per query, O(n)O(n) space
  3. O(log⁡n)O(\log n) per query whatever kk is, O(nk)O(nk) space
  4. O(log⁡n+k)O(\log n + k) per query, but only with O(nlog⁡n)O(n \log n) space
Show the answer

B. O(log⁡n+k)O(\log n + k) per query, O(n)O(n) space

Copying every second key of each augmented list into the one before it at most doubles the total size, and the bridges let each list after the first be searched with at most one step back: one binary search plus O(1)O(1) per list.

Further reading

  • J. L. Bentley & A. C.-C. Yao, "An almost optimal algorithm for unbounded searching," Information Processing Letters 5(3) (1976), 82–87.
  • Y. Perl, A. Itai & H. Avni, "Interpolation search—a log log N search," Communications of the ACM 21(7) (1978), 550–553.
  • A. C. Yao & F. F. Yao, "The complexity of searching an ordered random table," Proceedings of the 17th IEEE Symposium on Foundations of Computer Science (1976), 173–177.
  • B. Chazelle & L. J. Guibas, "Fractional cascading: I. A data structuring technique," Algorithmica 1 (1986), 133–162.
  • F. K. Hwang & S. Lin, "A simple algorithm for merging two disjoint linearly ordered sets," SIAM Journal on Computing 1(1) (1972), 31–39.