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
- Model
- Comparison model
- Properties
- comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
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 comparisons for lists of lengths and , 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 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 and of document ids, each strictly increasing. The output is the list of ids in both, in increasing order. For a query with terms, the input is 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.
INTERSECT(A, B) ▷ A and B strictly increasing- 1
R ← empty list, i ← 0, j ← 0 - 2
while i < |A| and j < |B| do - 3
if A[i] = B[j] then - 4
append A[i] to R, i ← i + 1, j ← j + 1 - 5
else if A[i] < B[j] then i ← i + 1 - 6
else j ← j + 1 - 7
return R INTERSECT-ALL(L_1, …, L_k)- 8
sort the lists so that |L_1| ≤ |L_2| ≤ … ≤ |L_k| - 9
R ← L_1 - 10
for t ← 2 to k while R is not empty do - 11
R ← INTERSECT(R, L_t) - 12
return R
Lines L3 and L5 make one three-way comparison. The loop reads and only, and and 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: and .
| step | line | |||||
|---|---|---|---|---|---|---|
| 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, and the loop stops. The merge made 4 comparisons; the bound is .
For the query sorted AND array AND search, line L8 orders the lists as search , array , sorted . The first merge compares 1 with 1, 7 with 2 and 7 with 8, and gives 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: holds the common ids of the prefixes and , in order, and no id of a passed prefix is in the part of the other list that is not yet passed. When , the id cannot be in , since all those ids are at least , and it is not in 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 . For INTERSECT-ALL, after step the list is the intersection of the first lists, so an empty 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 and be strictly increasing. A comparison is one three-way comparison of an id of with an id of , made in line L3 and finished in line L5 when the ids differ.
Invariant. Before each test of line L2:
(J) is the list of the ids of in increasing order. No id of is in , and no id of is in . Each id in is less than when , and less than when .
Initialization. Line L1 sets and empty. The prefixes are empty, so each statement of (J) holds.
Maintenance. Assume (J) and , . Write and .
- Case (lines L3 and L4). The new prefixes add to and to , so the new common set is the old one plus . Each id of is less than , so appending keeps in increasing order. For the second statement, is not in , because is strictly increasing and . The old ids of are not in , so they are not in either. The same holds with and swapped. For the third statement, and by the strict order.
- Case (line L5). The id is not in , because each id there is at least . It is not in either: if with , then would be an id of that is in , against (J). So is in no prefix of , the common set does not change, and is still right. The id is not in , which gives the second statement for the new . The other half of the second statement only loses an index of . The third statement holds because .
- Case (line L6). This is the case above with and swapped.
Termination. Each step increases by 1 or 2, and , so the loop ends after at most steps.
Theorem 1. INTERSECT returns in increasing order.
Proof. When the loop ends, or . Take the case ; the other case is symmetric. Let . Then is in , so by (J) it is not in . So is in , and by (J) it is in . Each id of is in both prefixes, so in . And is in increasing order by (J).
Theorem 2. If , INTERSECT makes at most comparisons. If or , it makes none. The bound is reached for each .
Proof. Each step of the loop makes one comparison and increases by at least 1. A step runs only when and , so before the step . Since before step , each step that runs has , that is . If one list is empty, line L2 fails at once.
For the tightness, let and . The lists have no common id, so each step increases by exactly 1. The first steps compare with , which are all smaller, and move to . The next steps compare with , which is larger than each of them, and move to . The loop then stops after steps.
Theorem 3. For lists with lengths after line L8, INTERSECT-ALL returns their intersection in increasing order, with at most comparisons in the loop of lines L10 and L11.
Proof. After the -th list is merged in, , by Theorem 1 and induction on . If is empty, the intersection of all lists is empty, so the early stop is right. The list before step is a subset of , so its length is at most , and Theorem 2 gives at most comparisons for step .
Remark. The bound of Theorem 2 is within an additive of the lower bound when . 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 by at least 1. A step runs only when and , so there are at most steps. The input , 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 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. time and extra space, besides the output, which has at most ids.
- Many lists. With , INTERSECT-ALL makes at most comparisons, since the list never has more than ids.
- Optimality. When , the bound is optimal in the comparison model: on the input , each of the pairs of neighbours comes from different lists and must be compared directly, as shown in the proof file of adaptive set intersection. When is much smaller than , the merge is far from the lower bound . For random ids and random ids below , 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 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 are less than , it makes only 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 lists at once with a heap and output an id that appears 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 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 then ". With "if then ", the pointer passes over ids of that may equal later ids of . On and , 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 and ". 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 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.
# 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 06R0D3 Edit this page History Report an error Markdown