Algorithm Search⌘K

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
Properties
comparison baseddeterministiciterative

Small-versus-small (SvS) is an algorithm for posting list intersection that sorts the kk 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 m≤nm \le n it makes at most 2mlog⁡2(1+n/m)+3m2m \log_2(1 + n/m) + 3m two-way comparisons, which is within a factor of 5 of the lower bound log⁡2(m+nm)\log_2 \binom{m+n}{m} 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 k≥1k \ge 1 lists L1,…,LkL_1, \ldots, L_k of document ids, each strictly increasing. The output is the list of the ids in all of them, in increasing order.

The algorithm

GALLOP(L,x,lo)(L, x, lo) returns the least index p≥lop \ge lo with L[p]≥xL[p] \ge x, or ∣L∣|L| if there is none. It probes lo,lo+1,lo+3,lo+7,…lo, lo + 1, lo + 3, lo + 7, \ldots until it finds an id at least xx, 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.

  1. SVS(L_1, …, L_k) ▷ each list strictly increasing
  2. 1sort the lists so that |L_1| ≤ |L_2| ≤ … ≤ |L_k|
  3. 2C ← L_1 ▷ the candidates
  4. 3for t ← 2 to k while C is not empty do
  5. 4R ← empty list, p ← 0
  6. 5for each x in C, in order do
  7. 6p ← GALLOP(L_t, x, p)
  8. 7if p = |L_t| then leave the loop of line L5
  9. 8if L_t[p] = x then append x to R, p ← p + 1
  10. 9C ← R
  11. 10return C

The search of line L6 starts at pp, not at 0. All ids of LtL_t before pp are smaller than the last candidate, so they are smaller than xx too.

Example

Intersect A=(7,20,40)A = (7, 20, 40) with B=(2,4,6,…,40)B = (2, 4, 6, \ldots, 40), the 20 even numbers from 2 to 40. Indices of BB start at 0, so B[i]=2i+2B[i] = 2i + 2.

candidate start pp probes of the doubling binary search answer pp B[p]B[p] tests output
7 0 B[0]=2B[0] = 2, B[1]=4B[1] = 4, B[3]=8B[3] = 8 B[2]=6B[2] = 6 3 8 4 + 1
20 3 B[3]=8B[3] = 8, B[4]=10B[4] = 10, B[6]=14B[6] = 14, B[10]=22B[10] = 22 B[8]=18B[8] = 18, B[9]=20B[9] = 20 9 20 6 + 1 20
40 10 B[10]=22B[10] = 22, B[11]=24B[11] = 24, B[13]=28B[13] = 28, B[17]=36B[17] = 36 B[19]=40B[19] = 40, B[18]=38B[18] = 38 19 40 6 + 1 40

For the candidate 40, the next probe would be at index 10+15=2510 + 15 = 25, 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 (20,40)(20, 40) after 19 tests. The bound is 2⋅3log⁡2(1+20/3)+9≈26.62 \cdot 3 \log_2(1 + 20/3) + 9 \approx 26.6. 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 (1,7)(1, 7), array (1,2,8)(1, 2, 8) and sorted (1,2,4,8)(1, 2, 4, 8). The candidates (1,7)(1, 7) 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 10610^6, 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 tt is L1∩⋯∩LtL_1 \cap \cdots \cap L_t. Inside one step, the loop keeps this invariant: each id of LtL_t before index pp is less than the current candidate. So GALLOP from pp finds the first id of the whole list that is at least xx, and xx is in LtL_t exactly when that id equals xx. If the search runs off the end, all ids of LtL_t are less than xx, so no later candidate can be in LtL_t, 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 LL of length nn we write GALLOP(L,x,lo)(L, x, lo) for the search of line L6, which is NEXT-GEQ of the posting list page: it returns the least index p≥lop \ge lo with L[p]≥xL[p] \ge x, or nn if there is none.

Lemma 1 (galloping). GALLOP(L,x,lo)(L, x, lo) with lo<nlo < n returns the index above. With g=p−log = p - lo, it makes 1 test when g=0g = 0 and at most 2⌊log⁡2g⌋+22 \lfloor \log_2 g \rfloor + 2 tests when g≥1g \ge 1. In both cases this is at most 2log⁡2(g+1)+22 \log_2(g + 1) + 2. With lo≥nlo \ge n it makes no test and returns lolo.

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 0,1,3,7,…,2t−10, 1, 3, 7, \ldots, 2^t - 1 all give <<, so g≥2tg \ge 2^t; one more probe may stop the doubling; the binary search runs on at most 2t−12^t - 1 indices and makes at most tt tests. The total is 1+t+1+t1 + t + 1 + t with t≤⌊log⁡2g⌋t \le \lfloor \log_2 g \rfloor. For g≥1g \ge 1, ⌊log⁡2g⌋≤log⁡2(g+1)\lfloor \log_2 g \rfloor \le \log_2(g+1); for g=0g = 0, 1≤21 \le 2. □\square

Lemma 2 (one step). Let CC be a strictly increasing list of rr candidates and LL a strictly increasing list of length nn. The loop of lines L4 to L8 sets the output list to C∩LC \cap L in increasing order, and makes at most 2rlog⁡2(1+n/r)+3r2r \log_2(1 + n/r) + 3r tests when r≥1r \ge 1.

Proof. We use this invariant, before the search for a candidate xx:

(S) Each id in L[0…p−1]L[0 \ldots p-1] is less than xx, and the output holds the candidates before xx that are in LL, in order.

Line L4 sets p=0p = 0 and the output is empty, so (S) holds for the first candidate. Line L6 returns the least p′≥pp' \ge p with L[p′]≥xL[p'] \ge x. By (S), no index below pp holds an id ≥x\ge x, so p′p' is the least index of LL with L[p′]≥xL[p'] \ge x. Hence x∈Lx \in L exactly when p′<np' < n and L[p′]=xL[p'] = x, which is the test of lines L7 and L8. If p′=np' = n, each id of LL is less than xx, so no later candidate, which is larger than xx, is in LL, and the break of line L7 is right. Otherwise let x′x' be the next candidate, with x′>xx' > x. If L[p′]=xL[p'] = x, line L8 adds xx and sets p=p′+1p = p' + 1; each id of L[0…p′]L[0 \ldots p'] is at most x<x′x < x'. If L[p′]>xL[p'] > x, then p=p′p = p', and each id of L[0…p′−1]L[0 \ldots p'-1] is less than x<x′x < x'. So (S) holds for x′x'. When the loop ends, the output is C∩LC \cap L in order.

For the count, let the loop search for r′≤rr' \le r candidates, and let g1,…,gr′g_1, \ldots, g_{r'} be the values of gg in Lemma 1 for these searches. The start of each search is at least the answer of the search before it, so the ranges [p,p′)[p, p') do not overlap and ∑igi≤n\sum_i g_i \le n. Each candidate costs at most 2log⁡2(gi+1)+22 \log_2(g_i + 1) + 2 tests in line L6 and one test in line L8. The function y↦log⁡2(1+y)y \mapsto \log_2(1 + y) is concave, so by Jensen's inequality

∑i=1r′log⁡2(1+gi)≤r′log⁡2(1+1r′∑igi)≤r′log⁡2(1+nr′).\sum_{i=1}^{r'} \log_2(1 + g_i) \le r' \log_2\left(1 + \frac{1}{r'} \sum_i g_i\right) \le r' \log_2\left(1 + \frac{n}{r'}\right).

So the step makes at most 2r′log⁡2(1+n/r′)+3r′2r' \log_2(1 + n/r') + 3r' tests. The function h(s)=slog⁡2(1+n/s)h(s) = s \log_2(1 + n/s) is nondecreasing for s>0s > 0: its derivative is log⁡2(1+y)−y(1+y)ln⁡2\log_2(1 + y) - \frac{y}{(1+y) \ln 2} with y=n/sy = n/s, and ln⁡(1+y)≥y1+y\ln(1 + y) \ge \frac{y}{1+y} for y≥0y \ge 0. With r′≤rr' \le r this gives the bound. If r′=0r' = 0, the step makes no test. □\square

Theorem. For lists L1,…,LkL_1, \ldots, L_k with lengths n1≤⋯≤nkn_1 \le \cdots \le n_k after line L1, SVS returns L1∩⋯∩LkL_1 \cap \cdots \cap L_k in increasing order. If n1≥1n_1 \ge 1, it makes at most

∑t=2k(2n1log⁡2(1+ntn1)+3n1)\sum_{t=2}^{k} \left( 2 n_1 \log_2\left(1 + \frac{n_t}{n_1}\right) + 3 n_1 \right)

tests. For k=2k = 2, m=n1m = n_1 and n=n2n = n_2, this is 2mlog⁡2(1+n/m)+3m2m \log_2(1 + n/m) + 3m, which is at most 5log⁡2(m+nm)5 \log_2 \binom{m+n}{m}.

Proof. By induction on tt, the candidate list after step tt is L1∩⋯∩LtL_1 \cap \cdots \cap L_t in increasing order: it holds for t=1t = 1 by line L2, and Lemma 2 gives the step from t−1t - 1 to tt. 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 L1L_1, so its size rr is at most n1n_1. By Lemma 2 and because hh is nondecreasing, step tt makes at most 2n1log⁡2(1+nt/n1)+3n12 n_1 \log_2(1 + n_t/n_1) + 3 n_1 tests.

For the last claim, (m+nm)=∏i=1mn+ii≥(m+nm)m\binom{m+n}{m} = \prod_{i=1}^{m} \frac{n+i}{i} \ge \left(\frac{m+n}{m}\right)^m, because n+ii≥n+mm\frac{n+i}{i} \ge \frac{n+m}{m} for 1≤i≤m1 \le i \le m. So log⁡2(m+nm)≥mlog⁡2(1+n/m)\log_2 \binom{m+n}{m} \ge m \log_2(1 + n/m). Since n≥mn \ge m, also mlog⁡2(1+n/m)≥mm \log_2(1 + n/m) \ge m. Hence 2mlog⁡2(1+n/m)+3m≤2log⁡2(m+nm)+3log⁡2(m+nm)2m \log_2(1 + n/m) + 3m \le 2 \log_2 \binom{m+n}{m} + 3 \log_2 \binom{m+n}{m}. ■\blacksquare

The lower bound ⌈log⁡2(m+nm)⌉\lceil \log_2 \binom{m+n}{m} \rceil 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 gg ids, it makes 1 test when g=0g = 0 and at most 2⌊log⁡2g⌋+22 \lfloor \log_2 g \rfloor + 2 tests when g≥1g \ge 1.
  • One step. For rr candidates and a list of length nn, the skips add up to at most nn, and by the concavity of the logarithm the step makes at most 2rlog⁡2(1+n/r)+3r2r \log_2(1 + n/r) + 3r two-way tests.
  • All steps. With n1≤⋯≤nkn_1 \le \cdots \le n_k, the candidates never number more than n1n_1, so SVS makes at most ∑t=2k(2n1log⁡2(1+nt/n1)+3n1)\sum_{t=2}^{k} \left(2 n_1 \log_2(1 + n_t/n_1) + 3 n_1\right) tests. For two lists this is O(mlog⁡(1+n/m))O(m \log(1 + n/m)).
  • Against the lower bound. For two lists, log⁡2(m+nm)≥mlog⁡2(1+n/m)≥m\log_2 \binom{m+n}{m} \ge m \log_2(1 + n/m) \ge m, so the bound 2mlog⁡2(1+n/m)+3m2m \log_2(1 + n/m) + 3m is at most 5 times the lower bound. When m=nm = n, it is about 5n5n tests, worse than the 2n−12n - 1 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 kk lengths. The extra space is the list of candidates, at most n1n_1 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, pp only grows, so each list is read from left to right, with jumps.
  • Not adaptive between lists. A candidate is searched in list tt only after it has passed all lists before tt. 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 pp to the end. Each search then costs about log⁡2(n−p)\log_2(n - p) tests, so the total is O(mlog⁡n)O(m \log n) instead of O(mlog⁡(1+n/m))O(m \log(1 + n/m)).
  • 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: "p←p \leftarrow GALLOP(Lt,x,p)(L_t, x, p)". With "p←p \leftarrow GALLOP(Lt,x,0)(L_t, x, 0)", each search costs up to about 2log⁡22 \log_2 of the index of its answer, and the total can reach about 2mlog⁡2n2m \log_2 n in place of 2mlog⁡2(1+n/m)+3m2m \log_2(1 + n/m) + 3m. The result is still right.
  • Not advancing after a match. Line L8 must set p←p+1p \leftarrow p + 1 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 ∣Lt∣|L_t|. Without it, line L8 reads Lt[∣Lt∣]L_t[|L_t|], past the end.
  • Wrong order of lists. Line L1 must sort by length. If the longest list of nn 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 nn searches, so the cost is linear in nn 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.

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
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

  1. 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
  2. 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
  3. 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.

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