Algorithmadvanced
Small-versus-small intersection
Also called SvS intersection.
Intersects many lists by taking the two shortest first and searching each candidate of the short list in the next one by galloping.
- Time
- O(m log(n/m + 1)) worstO(m) best
- Space
- O(m) extra
- Where
- k = the number of lists; m = the length of the shortest list; n = the length of the next list
- Model
- Comparison model
- Properties
- comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
Small-versus-small (SvS) is an algorithm for posting list intersection that sorts the lists by length, takes the shortest list as the set of candidates, and checks each candidate in the next list with a galloping search that starts where the last search ended. The candidates that survive are checked in the next list, and so on. For two lists of lengths it makes at most two-way comparisons, which is within a factor of 5 of the lower bound for every algorithm in the comparison model. Barbay, López-Ortiz, Lu and Salinger describe it as a simple and widely used method, and use it as a baseline for the adaptive algorithms.
In plain words
Suppose a query has three words, and the lists of their documents have 10, 5000 and 80000 entries. The answer can hold at most 10 documents, the ones of the shortest list. So take those 10 as candidates.
For each candidate, look for it in the next list. The candidates are sorted, so each search can start where the last one stopped. Each search jumps ahead by 1, then 2, then 4, then 8 places, until it passes the candidate, and then it narrows down with halving. A candidate that is not found is dropped. Then do the same with the next list, with only the candidates that are left.
The work grows with the number of candidates and only slowly with the length of the long list.
The problem
The input is lists of document ids, each strictly increasing. The output is the list of the ids in all of them, in increasing order.
The algorithm
GALLOP returns the least index with , or if there is none. It probes until it finds an id at least , then does a binary search in the last gap. It is the operation NEXT-GEQ of the posting list page, and a form of exponential search.
SVS(L_1, …, L_k) ▷ each list strictly increasing- 1
sort the lists so that |L_1| ≤ |L_2| ≤ … ≤ |L_k| - 2
C ← L_1 ▷ the candidates - 3
for t ← 2 to k while C is not empty do - 4
R ← empty list, p ← 0 - 5
for each x in C, in order do - 6
p ← GALLOP(L_t, x, p) - 7
if p = |L_t| then leave the loop of line L5 - 8
if L_t[p] = x then append x to R, p ← p + 1 - 9
C ← R - 10
return C
The search of line L6 starts at , not at 0. All ids of before are smaller than the last candidate, so they are smaller than too.
Example
Intersect with , the 20 even numbers from 2 to 40. Indices of start at 0, so .
| candidate | start | probes of the doubling | binary search | answer | tests | output | |
|---|---|---|---|---|---|---|---|
| 7 | 0 | , , | 3 | 8 | 4 + 1 | ||
| 20 | 3 | , , , | , | 9 | 20 | 6 + 1 | 20 |
| 40 | 10 | , , , | , | 19 | 40 | 6 + 1 | 40 |
For the candidate 40, the next probe would be at index , which is past the end, so the doubling stops without a test and the binary search runs on indices 18 and 19. The "+ 1" in each row is the equality test of line L8. The result is after 19 tests. The bound is . The merge of the same two lists takes 21 three-way steps, which is 40 two-way tests.
On the toy collection, the query sorted AND array AND search orders the lists as search , array and sorted . The candidates go into the list of "array": 1 is found at index 0 after 2 tests, and the search for 7 stops at the id 8 after 3 tests. The one candidate left, 1, is found in the list of "sorted" after 2 tests. The answer is document 1, after 7 tests.
The gain is large when the lengths differ a lot. For 10 random ids and 10000 random ids below , SvS made 210 tests, the bound of the next section is about 229.3, and the merge made 9956 three-way steps.
Correctness
The candidate list after step is . Inside one step, the loop keeps this invariant: each id of before index is less than the current candidate. So GALLOP from finds the first id of the whole list that is at least , and is in exactly when that id equals . If the search runs off the end, all ids of are less than , so no later candidate can be in , and line L7 may stop the step. The full proof, with the count of comparisons, is in the proof file below.
Proof: Small-versus-small returns the intersection with at most 2 m log2(1 + n/m) + 3 m tests for each listfull
All lists are strictly increasing. A test is one two-way comparison of ids, either or . For a list of length we write GALLOP for the search of line L6, which is NEXT-GEQ of the posting list page: it returns the least index with , or if there is none.
Lemma 1 (galloping). GALLOP with returns the index above. With , it makes 1 test when and at most tests when . In both cases this is at most . With it makes no test and returns .
Proof. The correctness and the first two counts are the theorem of the proof file of the posting list page, for the same procedure. In short: the probes at offsets all give , so ; one more probe may stop the doubling; the binary search runs on at most indices and makes at most tests. The total is with . For , ; for , .
Lemma 2 (one step). Let be a strictly increasing list of candidates and a strictly increasing list of length . The loop of lines L4 to L8 sets the output list to in increasing order, and makes at most tests when .
Proof. We use this invariant, before the search for a candidate :
(S) Each id in is less than , and the output holds the candidates before that are in , in order.
Line L4 sets and the output is empty, so (S) holds for the first candidate. Line L6 returns the least with . By (S), no index below holds an id , so is the least index of with . Hence exactly when and , which is the test of lines L7 and L8. If , each id of is less than , so no later candidate, which is larger than , is in , and the break of line L7 is right. Otherwise let be the next candidate, with . If , line L8 adds and sets ; each id of is at most . If , then , and each id of is less than . So (S) holds for . When the loop ends, the output is in order.
For the count, let the loop search for candidates, and let be the values of in Lemma 1 for these searches. The start of each search is at least the answer of the search before it, so the ranges do not overlap and . Each candidate costs at most tests in line L6 and one test in line L8. The function is concave, so by Jensen's inequality
So the step makes at most tests. The function is nondecreasing for : its derivative is with , and for . With this gives the bound. If , the step makes no test.
Theorem. For lists with lengths after line L1, SVS returns in increasing order. If , it makes at most
tests. For , and , this is , which is at most .
Proof. By induction on , the candidate list after step is in increasing order: it holds for by line L2, and Lemma 2 gives the step from to . If it becomes empty, the full intersection is empty, so the early stop of line L3 is right. Each candidate list is a subset of , so its size is at most . By Lemma 2 and because is nondecreasing, step makes at most tests.
For the last claim, , because for . So . Since , also . Hence .
The lower bound for each algorithm in the comparison model is proved in the proof file of adaptive set intersection. So SVS with galloping is optimal for two lists up to a factor of 5 in the worst case.
Complexity
- One search. If GALLOP skips ids, it makes 1 test when and at most tests when .
- One step. For candidates and a list of length , the skips add up to at most , and by the concavity of the logarithm the step makes at most two-way tests.
- All steps. With , the candidates never number more than , so SVS makes at most tests. For two lists this is .
- Against the lower bound. For two lists, , so the bound is at most 5 times the lower bound. When , it is about tests, worse than the steps of the merge, so the method is best for lists of different lengths.
- Time and space. The time is linear in the number of tests, plus the sort of lengths. The extra space is the list of candidates, at most ids.
Properties
- Shortest first. The candidate list never grows, and the first list sets the cost of all later steps.
- Each list in one direction. In one step, only grows, so each list is read from left to right, with jumps.
- Not adaptive between lists. A candidate is searched in list only after it has passed all lists before . A candidate that the last list would reject at once still costs a search in each list before it. The method of Demaine, López-Ortiz and Munro avoids this.
Variants and improvements
- Binary search from the last position. The original SvS of the experimental literature uses binary search over the rest of the list, from to the end. Each search then costs about tests, so the total is instead of .
- Swapping SvS. A variant that can swap the roles of the candidate list and the searched list, so that the search always runs from the list with fewer ids left. Barbay et al. credit it to Hwang and Lin.
- Small Adaptive. Search each candidate in all other lists before it moves to the next candidate, and keep the lists sorted by the number of ids that remain. Barbay et al. describe it as a mix of SvS and the adaptive method.
- Skips on compressed lists. On a compressed list, line L6 jumps with skip pointers or with a table of the first id of each block, then decodes one block.
- Divide and conquer. Baeza-Yates intersection has the same bound with a recursive split in place of the left-to-right scan.
- Galloping in all lists. The adaptive set intersection of Demaine, López-Ortiz and Munro gallops in all lists in turn with one candidate at a time.
When to use it
Use SvS for AND queries over posting lists of very different lengths, which is the common case for web queries with one rare and one common term. Use it when the lists support random access or have a block index. When all lists have about the same length, the merge makes fewer comparisons and has simpler branches.
Pitfalls
- Searching from 0. Line L6 must start at the last position: " GALLOP". With " GALLOP", each search costs up to about of the index of its answer, and the total can reach about in place of . The result is still right.
- Not advancing after a match. Line L8 must set after a match. Without it, the result is still right, but the next search makes one extra test at the old position.
- Missing the end test. Line L7 must stop the step when GALLOP returns . Without it, line L8 reads , past the end.
- Wrong order of lists. Line L1 must sort by length. If the longest list of ids is the candidate list, the first step makes a search for each of its ids until the short list runs out, which can be searches, so the cost is linear in again.
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
small_versus_small_intersection.py 54 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/small-versus-small-intersection/. The authors are listed in prov/39S9T4.jsonl.
from typing import Any, Sequence
def gallop(lst: Sequence[Any], x: Any, lo: int) -> int:
"""Return the least index p >= lo with lst[p] >= x, or len(lst) if there is none.
Precondition: lst is sorted. Only the test < is used. If g = p - lo, the call makes
one test when g = 0 and at most 2 floor(log2 g) + 2 tests when g >= 1, and no test
when lo >= len(lst).
"""
n = len(lst)
if lo >= n or not (lst[lo] < x):
return lo
b = 1
while lo + 2 * b - 1 < n and lst[lo + 2 * b - 1] < x:
b *= 2
a, c = lo + b, min(lo + 2 * b - 1, n)
while a < c:
q = (a + c) // 2
if lst[q] < x:
a = q + 1
else:
c = q
return a
def svs(lists: Sequence[Sequence[Any]]) -> list[Any]:
"""Return the ids that are in each list, in increasing order (small-versus-small).
Precondition: at least one list, each strictly increasing. The lists are taken by
increasing length. Each candidate of the current result is searched in the next list
by galloping from the place where the last search ended. Intersecting a candidate list
of size r with a list of size n makes at most 2 r log2(1 + n/r) + 3 r tests.
"""
order = sorted(lists, key=len) # @line L1
cand = list(order[0]) # @line L2
for t in range(1, len(order)): # @line L3
if not cand:
break
lst = order[t]
out: list[Any] = []
p = 0 # @line L4
for x in cand: # @line L5
p = gallop(lst, x, p) # @line L6
if p == len(lst): # @line L7
break
if lst[p] == x: # @line L8
out.append(x)
p += 1
cand = out # @line L9
return cand # @line L10
test_small_versus_small_intersection.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/small-versus-small-intersection/. The authors are listed in prov/39S9T4.jsonl.
import bisect
import math
import random
import irtoy
from small_versus_small_intersection import gallop, svs
class Counter:
def __init__(self) -> None:
self.n = 0
class Key:
"""An integer that counts each test 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.n += 1
return self.v < other.v
def __eq__(self, other: object) -> bool:
assert isinstance(other, Key)
self.c.n += 1
return self.v == other.v
def __hash__(self) -> int:
return hash(self.v)
def counted(lists: list[list[int]]) -> tuple[list[int], int]:
c = Counter()
r = svs([[Key(x, c) for x in lst] for lst in lists])
return [k.v for k in r], c.n
def bound(lengths: list[int]) -> float:
ns = sorted(lengths)
m = ns[0]
if m == 0:
return 0.0
return sum(2 * m * math.log2(1 + n / m) + 3 * m for n in ns[1:])
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 test_example() -> None:
a = [7, 20, 40]
b = list(range(2, 41, 2))
r, n = counted([b, a])
assert r == [20, 40]
assert n == 19
assert n <= bound([3, 20])
ix = postings()
r, n = counted([ix["sorted"], ix["array"], ix["search"]])
assert r == [1] and n == 7
def test_irtoy_queries() -> None:
ix = postings()
terms = sorted(ix)
rng = random.Random(8)
for _ in range(400):
q = rng.sample(terms, rng.randint(1, 4))
lists = [ix[t] for t in q]
r, n = counted(lists)
assert r == sorted(set(lists[0]).intersection(*lists[1:]))
assert n <= bound([len(x) for x in lists]) + 1e-9
for q in irtoy.QUERIES.values():
lists = [ix.get(t, []) for t in irtoy.tokenize(q)]
assert svs(lists) == sorted(set(lists[0]).intersection(*lists[1:]))
def test_edges() -> None:
assert svs([[]]) == []
assert svs([[], [1, 2]]) == []
assert svs([[1, 2, 3]]) == [1, 2, 3]
assert svs([[5], [5], [5]]) == [5]
assert svs([[1, 2], [3, 4]]) == []
assert gallop([], 3, 0) == 0
assert gallop([1, 2, 3], 9, 0) == 3
def test_gallop_against_bisect() -> None:
rng = random.Random(5)
for _ in range(1000):
lst = sorted(rng.sample(range(300), rng.randint(0, 80)))
lo = rng.randint(0, len(lst))
x = rng.randint(-3, 303)
c = Counter()
p = gallop([Key(v, c) for v in lst], Key(x, c), lo)
assert p == max(lo, bisect.bisect_left(lst, x))
g = p - lo
if lo < len(lst):
assert c.n <= (1 if g == 0 else 2 * math.floor(math.log2(g)) + 2)
def test_random_against_sets() -> None:
rng = random.Random(2009)
for _ in range(700):
k = rng.randint(1, 5)
u = rng.choice([30, 500, 100000])
lists = [sorted(rng.sample(range(u), rng.randint(0, min(u, rng.choice([5, 40, 400]))))) for _ in range(k)]
r, n = counted(lists)
assert r == sorted(set(lists[0]).intersection(*lists[1:]))
assert n <= bound([len(x) for x in lists]) + 1e-9
History
Moffat and Zobel in 1996 evaluated conjunctive queries from the term with the shortest list and checked each candidate in the longer lists with the help of skips, which is the SvS plan on compressed lists. Demaine, López-Ortiz and Munro in 2000 used galloping for intersection in their adaptive analysis. Barbay, López-Ortiz, Lu and Salinger in 2009 described SvS with binary and galloping search and compared it with the adaptive algorithms on a log of web queries. Culpepper and Moffat in 2010 studied the method on compressed lists, with hybrid representations for long lists.
References
- Jérémy Barbay, Alejandro López-Ortiz, Tyler Lu and Alejandro Salinger, An experimental investigation of set intersection algorithms for text searching, ACM Journal of Experimental Algorithmics 14, Article 3.7, 2009, the description of SvS (sort the sets by size, search each element of the smallest set in the others, with binary or galloping search from the last position), the Swapping SvS and Small Adaptive variants, and the experiments on web queries
- J. Shane Culpepper and Alistair Moffat, Efficient set intersection for inverted indexing, ACM Transactions on Information Systems 29(1), Article 1, 2010, the shortest-first intersection of posting lists with search in the longer lists, on uncompressed and compressed lists
- Alistair Moffat and Justin Zobel, Self-indexing inverted files for fast text retrieval, ACM Transactions on Information Systems 14(4), 349-379, 1996, the evaluation of conjunctive queries from the rarest term, with candidates checked in the longer lists through skips
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 39S9T4 Edit this page History Report an error Markdown