Algorithm Search⌘K

Algorithmintro

Merge-based list intersection

Also called linear merge intersection.

Walks two sorted posting lists with one pointer each and advances the smaller, in time linear in the sum of the lengths.

Time
O(m + n) worstΘ(m) best
Space
O(1) extra
Where
k = the number of lists; m = the length of the shorter list; n = the length of the longer list
Properties
comparison baseddeterministiciterative

Merge-based list intersection finds the common document ids of two sorted posting lists by walking both with one pointer each: if the two ids are equal it outputs the id and advances both, else it advances the pointer at the smaller id. It solves posting list intersection with at most m+n−1m + n - 1 comparisons for lists of lengths mm and nn, and it reads each list only from left to right, so it works on compressed lists that can only be decoded in order. The same two-pointer scan on plain arrays is on the page sorted array intersection, which treats general arrays with repeated values and the search-based variants; this page is about the index setting, where the ids are strictly increasing, the lists come from a posting list store, and a query with kk terms needs an order in which to intersect the lists.

In plain words

Put two sorted lists of document numbers side by side, with a finger on the first number of each. Look at the two numbers under your fingers. If they are equal, write the number down and move both fingers. If they are not, the smaller number cannot be in the other list any more, because the other list has only bigger numbers left. So move the finger that is on the smaller number. Stop when a finger falls off the end of its list.

For a query with many words, take the two shortest lists first. Their common part is short, and each next step works with that short list.

The problem

The input is two lists A[0…m−1]A[0 \ldots m-1] and B[0…n−1]B[0 \ldots n-1] of document ids, each strictly increasing. The output is the list of ids in both, in increasing order. For a query with k≥1k \ge 1 terms, the input is kk such lists, and the output is the ids in all of them.

The algorithm

INTERSECT is the two-list merge. INTERSECT-ALL runs it on the lists of a query, shortest first.

  1. INTERSECT(A, B) ▷ A and B strictly increasing
  2. 1R ← empty list, i ← 0, j ← 0
  3. 2while i < |A| and j < |B| do
  4. 3if A[i] = B[j] then
  5. 4append A[i] to R, i ← i + 1, j ← j + 1
  6. 5else if A[i] < B[j] then i ← i + 1
  7. 6else j ← j + 1
  8. 7return R
  9. INTERSECT-ALL(L_1, …, L_k)
  10. 8sort the lists so that |L_1| ≤ |L_2| ≤ … ≤ |L_k|
  11. 9R ← L_1
  12. 10for t ← 2 to k while R is not empty do
  13. 11R ← INTERSECT(R, L_t)
  14. 12return R

Lines L3 and L5 make one three-way comparison. The loop reads A[i]A[i] and B[j]B[j] only, and ii and jj only grow, so a cursor that decodes the next id of a compressed list is enough.

Example

Intersect the lists of "sorted" and "array" from the toy collection: A=(1,2,4,8)A = (1, 2, 4, 8) and B=(1,2,8)B = (1, 2, 8).

step ii jj A[i]A[i] B[j]B[j] line RR
1 0 0 1 1 L4 1
2 1 1 2 2 L4 1, 2
3 2 2 4 8 L5 1, 2
4 3 2 8 8 L4 1, 2, 8

After step 4, i=4=∣A∣i = 4 = |A| and the loop stops. The merge made 4 comparisons; the bound is 4+3−1=64 + 3 - 1 = 6.

For the query sorted AND array AND search, line L8 orders the lists as search (1,7)(1, 7), array (1,2,8)(1, 2, 8), sorted (1,2,4,8)(1, 2, 4, 8). The first merge compares 1 with 1, 7 with 2 and 7 with 8, and gives (1)(1) after 3 comparisons. The second merge compares 1 with 1 and stops after 1 comparison. The answer is document 1, after 4 comparisons.

Correctness

The loop keeps this invariant: RR holds the common ids of the prefixes A[0…i−1]A[0 \ldots i-1] and B[0…j−1]B[0 \ldots j-1], in order, and no id of a passed prefix is in the part of the other list that is not yet passed. When A[i]<B[j]A[i] < B[j], the id A[i]A[i] cannot be in B[j…]B[j \ldots], since all those ids are at least B[j]B[j], and it is not in B[0…j−1]B[0 \ldots j-1] by the invariant. So line L5 can drop it. When the loop stops, one list is used up, and each of its ids that is in the other list is in RR. For INTERSECT-ALL, after step tt the list RR is the intersection of the first tt lists, so an empty RR means an empty answer. The full proof is in the proof file below.

Proof: The merge returns the common ids in order with at most m + n - 1 comparisonsfull

Let A[0…m−1]A[0 \ldots m-1] and B[0…n−1]B[0 \ldots n-1] be strictly increasing. A comparison is one three-way comparison of an id of AA with an id of BB, made in line L3 and finished in line L5 when the ids differ.

Invariant. Before each test of line L2:

(J) RR is the list of the ids of A[0…i−1]∩B[0…j−1]A[0 \ldots i-1] \cap B[0 \ldots j-1] in increasing order. No id of A[0…i−1]A[0 \ldots i-1] is in B[j…n−1]B[j \ldots n-1], and no id of B[0…j−1]B[0 \ldots j-1] is in A[i…m−1]A[i \ldots m-1]. Each id in RR is less than A[i]A[i] when i<mi < m, and less than B[j]B[j] when j<nj < n.

Initialization. Line L1 sets i=j=0i = j = 0 and RR empty. The prefixes are empty, so each statement of (J) holds.

Maintenance. Assume (J) and i<mi < m, j<nj < n. Write x=A[i]x = A[i] and y=B[j]y = B[j].

  • Case x=yx = y (lines L3 and L4). The new prefixes add xx to AA and y=xy = x to BB, so the new common set is the old one plus xx. Each id of RR is less than xx, so appending xx keeps RR in increasing order. For the second statement, xx is not in B[j+1…]B[j+1 \ldots], because BB is strictly increasing and B[j]=xB[j] = x. The old ids of A[0…i−1]A[0 \ldots i-1] are not in B[j…]B[j \ldots], so they are not in B[j+1…]B[j+1 \ldots] either. The same holds with AA and BB swapped. For the third statement, x<A[i+1]x < A[i+1] and x<B[j+1]x < B[j+1] by the strict order.
  • Case x<yx < y (line L5). The id xx is not in B[j…]B[j \ldots], because each id there is at least y>xy > x. It is not in B[0…j−1]B[0 \ldots j-1] either: if x=B[q]x = B[q] with q<jq < j, then B[q]B[q] would be an id of B[0…j−1]B[0 \ldots j-1] that is in A[i…]A[i \ldots], against (J). So xx is in no prefix of BB, the common set does not change, and RR is still right. The id xx is not in B[j…]B[j \ldots], which gives the second statement for the new ii. The other half of the second statement only loses an index of A[i…]A[i \ldots]. The third statement holds because A[i+1]>A[i]A[i+1] > A[i].
  • Case x>yx > y (line L6). This is the case above with AA and BB swapped.

Termination. Each step increases i+ji + j by 1 or 2, and i+j≤m+ni + j \le m + n, so the loop ends after at most m+nm + n steps.

Theorem 1. INTERSECT(A,B)(A, B) returns A∩BA \cap B in increasing order.

Proof. When the loop ends, i=mi = m or j=nj = n. Take the case i=mi = m; the other case is symmetric. Let z∈A∩Bz \in A \cap B. Then zz is in A[0…m−1]A[0 \ldots m-1], so by (J) it is not in B[j…n−1]B[j \ldots n-1]. So zz is in B[0…j−1]B[0 \ldots j-1], and by (J) it is in RR. Each id of RR is in both prefixes, so in A∩BA \cap B. And RR is in increasing order by (J). □\square

Theorem 2. If m,n≥1m, n \ge 1, INTERSECT(A,B)(A, B) makes at most m+n−1m + n - 1 comparisons. If m=0m = 0 or n=0n = 0, it makes none. The bound m+n−1m + n - 1 is reached for each m,n≥1m, n \ge 1.

Proof. Each step of the loop makes one comparison and increases i+ji + j by at least 1. A step runs only when i≤m−1i \le m - 1 and j≤n−1j \le n - 1, so before the step i+j≤m+n−2i + j \le m + n - 2. Since i+j≥t−1i + j \ge t - 1 before step tt, each step tt that runs has t−1≤m+n−2t - 1 \le m + n - 2, that is t≤m+n−1t \le m + n - 1. If one list is empty, line L2 fails at once.

For the tightness, let B=(1,2,…,n−1,n+m)B = (1, 2, \ldots, n-1, n+m) and A=(n,n+1,…,n+m−1)A = (n, n+1, \ldots, n+m-1). The lists have no common id, so each step increases i+ji + j by exactly 1. The first n−1n - 1 steps compare A[0]=nA[0] = n with B[0],…,B[n−2]B[0], \ldots, B[n-2], which are all smaller, and move jj to n−1n - 1. The next mm steps compare A[0],…,A[m−1]A[0], \ldots, A[m-1] with B[n−1]=n+mB[n-1] = n + m, which is larger than each of them, and move ii to mm. The loop then stops after m+n−1m + n - 1 steps. □\square

Theorem 3. For k≥1k \ge 1 lists with lengths n1≤n2≤⋯≤nkn_1 \le n_2 \le \cdots \le n_k after line L8, INTERSECT-ALL returns their intersection in increasing order, with at most ∑t=2k(n1+nt−1)\sum_{t=2}^{k} (n_1 + n_t - 1) comparisons in the loop of lines L10 and L11.

Proof. After the tt-th list is merged in, R=L1∩⋯∩LtR = L_1 \cap \cdots \cap L_t, by Theorem 1 and induction on tt. If RR is empty, the intersection of all lists is empty, so the early stop is right. The list RR before step tt is a subset of L1L_1, so its length is at most n1n_1, and Theorem 2 gives at most n1+nt−1n_1 + n_t - 1 comparisons for step tt. ■\blacksquare

Remark. The bound of Theorem 2 is within an additive O(log⁡n)O(\log n) of the lower bound ⌈log⁡2(2nn)⌉\lceil \log_2 \binom{2n}{n} \rceil when m=nm = n. The lower bound, with its proof by a counting argument, is in the proof file of adaptive set intersection.

Complexity

  • Comparisons, two lists. Each step makes one comparison and increases i+ji + j by at least 1. A step runs only when i≤m−1i \le m - 1 and j≤n−1j \le n - 1, so there are at most m+n−1m + n - 1 steps. The input B=(1,2,…,n−1,n+m)B = (1, 2, \ldots, n-1, n+m), A=(n,…,n+m−1)A = (n, \ldots, n+m-1) reaches this bound. With two-way tests in place of the three-way comparison, each step makes at most 2 tests.
  • Best case. The loop needs at least min⁡(m,n)\min(m, n) steps, because each step advances each pointer by at most 1. This is reached, for example, when the shorter list is a prefix of the longer one.
  • Time and space. O(m+n)O(m + n) time and O(1)O(1) extra space, besides the output, which has at most min⁡(m,n)\min(m, n) ids.
  • Many lists. With n1≤⋯≤nkn_1 \le \cdots \le n_k, INTERSECT-ALL makes at most ∑t=2k(n1+nt−1)\sum_{t=2}^{k} (n_1 + n_t - 1) comparisons, since the list RR never has more than n1n_1 ids.
  • Optimality. When m=nm = n, the bound 2n−12n - 1 is optimal in the comparison model: on the input a1<b1<a2<b2<⋯<an<bna_1 < b_1 < a_2 < b_2 < \cdots < a_n < b_n, each of the 2n−12n - 1 pairs of neighbours comes from different lists and must be compared directly, as shown in the proof file of adaptive set intersection. When mm is much smaller than nn, the merge is far from the lower bound log⁡2(m+nm)\log_2 \binom{m+n}{m}. For m=10m = 10 random ids and n=10000n = 10000 random ids below 10610^6, the merge made 9956 comparisons, against a lower bound of about 111.

Properties

  • One pass, in order. Each list is read once, from left to right. This suits compressed lists and lists on disk.
  • Output in order. The result is a sorted list of ids, so it can be the input of the next merge.
  • Not adaptive to length ratio. The cost depends on how far the pointers move, which is up to m+nm + n even when one list is short.
  • Adaptive to the data in one way. The loop stops as soon as one list ends. If all ids of AA are less than B[0]B[0], it makes only mm comparisons.

Variants and improvements

  • Skip pointers. Store forward pointers in the long list, and follow one when its target is still at most the id in the other list. See skip pointers.
  • Galloping. Replace the step of one position in line L5 or L6 by a doubling search for the first id at least the other id. With the search only in the longer list, this is small-versus-small; with the search in both, it is the method of Demaine, López-Ortiz and Munro, see adaptive set intersection.
  • Divide and conquer. Search the median of the short list in the long list and recurse on both sides. See Baeza-Yates intersection.
  • k-way merge. Merge all kk lists at once with a heap and output an id that appears kk times. This is the form that document-at-a-time evaluation uses for ranked queries, but for AND it does more work than the shortest-first order.
  • Union and difference. OR outputs each id that is in either list, with one copy of a common id; AND NOT outputs A[i]A[i] in line L5 and drops it in line L4.
  • Positional merge. In each common document, merge the position lists to test a phrase. See positional intersection.

When to use it

Use the merge when the two lists have similar lengths, or when the lists are compressed with no way to jump. It is simple, it has no branches that depend on a search, and it reads memory in order. When one list is much shorter than the other, a search-based method such as small-versus-small makes far fewer comparisons.

Pitfalls

  • Advancing the wrong pointer. Line L5 must advance the pointer at the smaller id: "if A[i]<B[j]A[i] < B[j] then i←i+1i \leftarrow i + 1". With "if A[i]<B[j]A[i] < B[j] then j←j+1j \leftarrow j + 1", the pointer passes over ids of BB that may equal later ids of AA. On A=(3,5)A = (3, 5) and B=(4,5)B = (4, 5), that version compares 3 with 4 and moves past 4, then compares 3 with 5 and moves past 5, and it returns an empty list although 5 is in both.
  • Or in place of and. Line L2 must be "while i<∣A∣i < |A| and j<∣B∣j < |B|". With "or", the loop reads past the end of the list that is used up.
  • The query order. Line L8 must sort the lists by length. In the query order, posting AND list AND merge first gives (3,4)(3, 4) after 2 comparisons and then needs 3 more; shortest first, list AND merge is empty after 3 comparisons and the loop stops. On a real index, a common term first can make the first merge cost millions of steps.
  • Lists with repeated ids. The proof needs strictly increasing lists. If a bad build puts the same id twice in each list, line L4 outputs it twice.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

irtoy.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.

Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""

DOCS = {
    1: "binary search finds a key in a sorted array",
    2: "merge sort merges two sorted runs into one sorted array",
    3: "an inverted index maps each term to a posting list",
    4: "a posting list is a sorted list of document ids",
    5: "skip pointers speed up the merge of two posting lists",
    6: "a hash table finds a key in constant expected time",
    7: "search engines rank documents by a score for the query",
    8: "the sorted array of ids is compressed with gap encoding",
}

N = len(DOCS)

QUERIES = {
    "q1": "sorted array search",
    "q2": "posting list merge",
    "q3": "rank documents",
    "q4": "quantum circuit",
}

# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
    "q1": {1: 2, 2: 1, 8: 1},
    "q2": {5: 2, 4: 1, 3: 1},
    "q3": {7: 2},
    "q4": {},
}

# A fixed run for the metric pages, as scores per query.
RUN = {
    "q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}


def tokenize(text):
    """Lower-case words split on spaces."""
    return text.lower().split()


_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}


def tf(term, doc_id):
    """Number of times term occurs in document doc_id."""
    return _TOKENS[doc_id].count(term)


def df(term):
    """Number of documents that contain term."""
    return sum(1 for toks in _TOKENS.values() if term in toks)


def cf(term):
    """Number of occurrences of term in the whole collection."""
    return sum(toks.count(term) for toks in _TOKENS.values())


def doc_len(doc_id):
    """Number of tokens in document doc_id."""
    return len(_TOKENS[doc_id])


def avgdl():
    """Average document length in tokens."""
    return sum(len(toks) for toks in _TOKENS.values()) / N
merge_based_list_intersection.py 40 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/merge-based-list-intersection/. The authors are listed in prov/06R0D3.jsonl.

from typing import Any, Sequence


def intersect(a: Sequence[Any], b: Sequence[Any]) -> list[Any]:
    """Return the ids that are in both a and b, in increasing order.

    Precondition: a and b are strictly increasing. Each step of the loop makes one
    three-way comparison (a test == and, when it fails, a test <), and the loop runs
    at most len(a) + len(b) - 1 times, so the time is O(len(a) + len(b)).
    """
    r: list[Any] = []
    i, j = 0, 0  # @line L1
    while i < len(a) and j < len(b):  # @line L2
        if a[i] == b[j]:  # @line L3
            r.append(a[i])  # @line L4
            i += 1
            j += 1
        elif a[i] < b[j]:  # @line L5
            i += 1
        else:
            j += 1  # @line L6
    return r  # @line L7


def intersect_all(lists: Sequence[Sequence[Any]]) -> list[Any]:
    """Return the ids that are in each list, in increasing order.

    Precondition: at least one list, each strictly increasing. The lists are taken in
    order of increasing length, two at a time, and the work stops when the result is empty.
    """
    order = sorted(lists, key=len)  # @line L8
    r = list(order[0])  # @line L9
    for t in range(1, len(order)):  # @line L10
        if not r:
            break
        r = intersect(r, order[t])  # @line L11
    return r  # @line L12
test_merge_based_list_intersection.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/merge-based-list-intersection/. The authors are listed in prov/06R0D3.jsonl.

import itertools
import random

import irtoy
from merge_based_list_intersection import intersect, intersect_all


class Counter:
    def __init__(self) -> None:
        self.eq = 0
        self.lt = 0


class Key:
    """An integer that counts the tests it takes part in."""

    def __init__(self, v: int, c: Counter) -> None:
        self.v, self.c = v, c

    def __lt__(self, other: "Key") -> bool:
        self.c.lt += 1
        return self.v < other.v

    def __eq__(self, other: object) -> bool:
        assert isinstance(other, Key)
        self.c.eq += 1
        return self.v == other.v

    def __hash__(self) -> int:
        return hash(self.v)


def postings() -> dict[str, list[int]]:
    index: dict[str, list[int]] = {}
    for d in sorted(irtoy.DOCS):
        for t in sorted(set(irtoy.tokenize(irtoy.DOCS[d]))):
            index.setdefault(t, []).append(d)
    return index


def counted(a: list[int], b: list[int]) -> tuple[list[int], Counter]:
    c = Counter()
    r = intersect([Key(x, c) for x in a], [Key(x, c) for x in b])
    return [k.v for k in r], c


def test_example() -> None:
    ix = postings()
    r, c = counted(ix["sorted"], ix["array"])
    assert r == [1, 2, 8]
    assert c.eq == 4
    assert intersect_all([ix["sorted"], ix["array"], ix["search"]]) == [1]
    assert intersect_all([ix["posting"], ix["list"], ix["merge"]]) == []
    r, c = counted(ix["search"], ix["array"])
    assert r == [1] and c.eq == 3
    r, c = counted(r, ix["sorted"])
    assert r == [1] and c.eq == 1


def test_worst_case_is_tight() -> None:
    r, c = counted([1, 3, 5], [2, 4, 6])
    assert r == [] and c.eq == 5


def test_irtoy_all_pairs_and_triples() -> None:
    ix = postings()
    terms = sorted(ix)
    for s, t in itertools.combinations(terms, 2):
        r, c = counted(ix[s], ix[t])
        assert r == sorted(set(ix[s]) & set(ix[t]))
        assert c.eq <= len(ix[s]) + len(ix[t]) - 1
    for q in irtoy.QUERIES.values():
        lists = [ix.get(t, []) for t in irtoy.tokenize(q)]
        want = set(lists[0]).intersection(*lists[1:])
        assert intersect_all(lists) == sorted(want)


def test_edges() -> None:
    assert intersect([], []) == []
    assert intersect([1, 2], []) == []
    assert intersect([], [1]) == []
    assert intersect([5], [5]) == [5]
    assert intersect_all([[1, 2, 3]]) == [1, 2, 3]
    r, c = counted([1, 2, 3], [7])
    assert r == [] and c.eq == 3


def test_random_against_sets() -> None:
    rng = random.Random(1996)
    for _ in range(1500):
        u = rng.choice([10, 50, 1000])
        a = sorted(rng.sample(range(u), rng.randint(0, min(u, 60))))
        b = sorted(rng.sample(range(u), rng.randint(0, min(u, 60))))
        r, c = counted(a, b)
        assert r == sorted(set(a) & set(b))
        if a and b:
            assert c.eq <= len(a) + len(b) - 1
            assert c.lt <= c.eq
        else:
            assert c.eq == 0
    for _ in range(300):
        lists = [sorted(rng.sample(range(80), rng.randint(0, 40))) for _ in range(rng.randint(1, 6))]
        want = set(lists[0]).intersection(*lists[1:])
        assert intersect_all(lists) == sorted(want)

History

The two-pointer merge of sorted lists is far older than search engines; Knuth gives the theory of merging with the fewest comparisons, including the result that the straight merge is optimal for two lists of equal length. Manning, Raghavan and Schuetze present the merge as the INTERSECT algorithm of their first chapter, with the rule to process the terms in order of increasing document frequency. Culpepper and Moffat compare it with search-based and hybrid methods on compressed and uncompressed lists.

References

  1. Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 1, Section 1.3 (the INTERSECT algorithm for two postings lists, its time linear in the total length, and the processing of terms in order of increasing document frequency)
  2. Donald E. Knuth, The Art of Computer Programming, Volume 3, second edition, Section 5.3.2 (minimum-comparison merging, and the optimality of the straight merge when the two lists have equal length)
  3. J. Shane Culpepper and Alistair Moffat, Efficient set intersection for inverted indexing, ACM Transactions on Information Systems 29(1), Article 1, 2010, the intersection methods for uncompressed and compressed posting lists, from the plain merge to the search-based and hybrid methods

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example