Back

Interpolation Search

Intermediate
Search
Requires sorted array

Interpolation Search uses a formula to predict where the target likely is — like how a human opens a dictionary near "Z" for a word starting with Z. On uniformly distributed data it achieves O(log log n), beating Binary Search. Watch the Probe (P) jump directly toward the target.

Auto-sorted: Interpolation Search requires sorted data. For uniform distributions, the probe formula jumps much closer to the target than Binary Search's midpoint.

Search Target

Quick examples:

↑ Set a target value above to begin searching the array

Loading controls...
Loading visualization...
Uniform: O(log log n)
Space: O(1)

Legend

Probe (P)
Interpolated position being compared
Found!
Target located here
Active Window
Elements within [Low … High]
Eliminated
Faded — discarded this step
Not Found
Search exhausted
— — — target: N
Dashed line = target height
Pointer labels:
LLow boundary
PProbe (interpolated)
HHigh boundary
Found position
Key insight:
P jumps proportionally to where target's value sits in range

Inspector

No active frame to inspect

Reference implementation of Interpolation Search. Select a language tab to view and copy the code.

def interpolation_search(arr: list[int], target: int) -> int:
    low, high = 0, len(arr) - 1
    while low <= high and arr[low] <= target <= arr[high]:
        if low == high:
            return low if arr[low] == target else -1
        # Probe position via linear interpolation
        pos = low + (target - arr[low]) * (high - low) // (arr[high] - arr[low])
        if arr[pos] == target:
            return pos
        elif arr[pos] < target:
            low  = pos + 1
        else:
            high = pos - 1
    return -1

Python — Code Walkthrough

  1. Chained comparison for the range guard

    arr[low] <= target <= arr[high]

    Python allows chaining comparison operators. arr[low] <= target <= arr[high] reads naturally and is equivalent to arr[low] <= target and target <= arr[high].

  2. Floor division // prevents float index

    pos = low + (target - arr[low]) * (high - low) // (arr[high] - arr[low])

    Python's / operator returns a float. Using // (floor division) keeps pos an integer suitable for use as an index. Python's arbitrary-precision integers also prevent overflow.

  3. Division-by-zero guard

    if low == high: return low if arr[low] == target else -1

    When low equals high, arr[high] − arr[low] = 0 which would raise ZeroDivisionError. This check handles the degenerate one-element window.

  4. elif chain for clarity

    if arr[pos] == target ... elif arr[pos] < target ... else

    Three mutually exclusive outcomes: found (return pos), probe too low (advance low), probe too high (retreat high). Python elif avoids nested ifs.