Algorithmadvanced
Baeza-Yates intersection
Also called double binary search intersection.
Searches the median of the shorter list in the longer one and recurses on both halves, adapting to the ratio of the list lengths.
- Time
- O(m log(n/m + 1)) worst
- Space
- O(log m) extra
- Where
- m = the length of the shorter list; n = the length of the longer list
- Model
- Comparison model
- Properties
- comparison baseddeterministicrecursive
- Evidence
- Proof sketchCode in 1 languages
Baeza-Yates intersection computes the common ids of two sorted lists by divide and conquer: it takes the median of the shorter list, finds its place in the longer list by binary search, and recurses on the two left parts and on the two right parts. Ricardo Baeza-Yates published it in 2004 for posting list intersection. For lists of lengths it makes at most two-way comparisons, so it is within a constant factor of the lower bound for every ratio of the lengths. When the lengths are equal it costs , like the merge, and when one list is very short it costs about a binary search for each of its ids.
In plain words
Take the shorter list and pick the number in its middle. Look it up in the longer list with a halving search. This cuts the longer list in two at that place. Everything in the left half of the short list can only match something in the left part of the long list, and the same is true on the right. So the problem breaks into two smaller problems of the same kind, one on each side, plus a check of the middle number itself.
Solve each side the same way. At each new step, take the middle of whichever list is shorter now. A side with an empty list has no common numbers and needs no work.
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 lists, the method runs on two lists at a time, from the shortest.
The algorithm
The call BY appends to the output . The ranges are half-open: holds .
BY(A, alo, ahi, B, blo, bhi) ▷ appends A[alo..ahi) ∩ B[blo..bhi) to R- 1
if ahi - alo > bhi - blo then swap (A, alo, ahi) and (B, blo, bhi) - 2
if alo = ahi then return ▷ the smaller range is empty - 3
mid ← alo + ⌊(ahi - alo) / 2⌋, x ← A[mid] - 4
p ← the least index in [blo, bhi] with p = bhi or B[p] ≥ x ▷ binary search - 5
BY(A, alo, mid, B, blo, p) - 6
if p < bhi and B[p] = x then append x to R, p ← p + 1 - 7
BY(A, mid + 1, ahi, B, p, bhi)
Line L1 keeps the median in the smaller range at each call, so the smaller range at least halves from a call to its children. Line L6 sits between the two calls, so the ids go to in increasing order.
Example
Intersect with , the 20 even numbers from 2 to 40, with indices from 0, so .
| call | smaller range | larger range | probes of line L4 | line L6 | tests | ||
|---|---|---|---|---|---|---|---|
| root | 20 | , , , | 9 | output 20 | 4 + 1 | ||
| left | 7 | , , | 3 | 3 + 1 | |||
| right | 40 | , , | 19 | output 40 | 3 + 1 |
The four calls below these have an empty range of and return at line L2. The result is after 13 tests. Small-versus-small makes 19 tests on the same input and the merge makes 21 three-way steps. The bound of this page is .
On the toy collection, sorted AND array is BY on and , with the result , and the query sorted AND array AND search gives document 1.
For 10 random ids and 10000 random ids below , the method made 125 tests. The bound is about 259.4, the lower bound is about 111.1, and the merge made 9956 steps.
Correctness
Let and let be its place in the larger range. The ids of are less than and the ids of are at least , so each common id less than is in the two left parts. In the same way, each common id greater than is in the two right parts, and itself is common exactly when . The two calls work on ranges with fewer ids in total, so by induction they output the common ids of their parts, in order. The full proof, with the count of comparisons, is in the proof file below.
Proof: Baeza-Yates intersection returns the intersection with at most 2 m log2(2 + n/m) + 6 m testsfull
Both lists are strictly increasing. A call BY works on the two half-open ranges. A test is one two-way comparison of ids, or . Line L4 is a binary search for the least index in with or .
Lemma 1 (binary search). On a range of indices, line L4 returns the index above and makes at most tests.
Proof. This is Lemma 2 of the proof file of the posting list page: each test keeps the answer in the range and cuts the size to at most , so the size reaches 0 after at most tests when , and after 0 tests when .
Theorem 1 (correctness). A call BY on the ranges and appends to the output exactly the ids of , in increasing order.
Proof. By strong induction on the total size . Line L1 may swap the two ranges; the intersection does not change, so we may assume that is the smaller range. If it is empty, the intersection is empty and line L2 returns with no output. Else line L3 picks with , and line L4 finds .
Split the common ids into three parts. An id that is in both ranges lies in , because is increasing, and in , because each id of is at least . An id is in the range exactly when and . An id lies in , and in , where if and otherwise, because each id of is at most . Conversely, each id in one of these three parts is common to the two ranges.
Lines L5 and L7 are calls on ranges with a smaller total size, because the index is in neither range. By the induction hypothesis, line L5 appends the ids of the first part in increasing order, line L6 appends if it is common, and line L7 appends the ids of the third part in increasing order. The ids of the first part are less than and those of the third part are greater, so the whole output of the call is in increasing order.
Theorem 2 (count). Let and . BY makes at most
tests.
Proof. Call a node of the recursion tree working if, after line L1, its smaller range is not empty. Only working nodes make tests. A working node whose larger range has indices makes at most tests in line L4 and one test in line L6, so at most tests.
Depth. Let be the size of the smaller range of . The two children of get the parts of that range before and after , of sizes and , both at most . The smaller range of a child is at most the part it gets, so at least halves from a node to its child. The root has , so a working node at depth has , which gives . A level has at most nodes.
Disjoint ranges. At one depth, the ranges of of the nodes do not overlap, and the ranges of do not overlap. This holds at the root, and a call passes to its two children disjoint parts of its own two ranges. So over the working nodes of one depth.
One level. Let be the number of working nodes at depth . By Jensen's inequality for the concave function , and because is nondecreasing in for each (its derivative is with ),
All levels. Write , so , and put . Since for and ,
With and , this is at most , and since is nondecreasing and , it is at most . The number of working nodes is at most , so the terms "" add at most . The total is at most .
The other forms. From for , , which gives the middle form. For the last form, , so , and this is at least because . So .
Remark. The lower bound for every algorithm in the comparison model is proved in the proof file of adaptive set intersection. So the method is optimal up to a constant factor of at most 10 for each ratio of the lengths. The constant comes from this proof and is not tight: on 3000 random pairs with and , no pair used more than half of the bound .
Complexity
- Comparisons. At most two-way tests for . The proof counts the recursion level by level: level has at most working calls, the ranges of one level do not overlap, and the depth is at most . Jensen's inequality bounds the cost of the binary searches of one level, and the sum over the levels is a geometric series.
- Against the lower bound. The bound is at most , so the method is optimal up to a constant factor. When , it is about tests in the worst case, more than the steps of the merge; on random lists the count is far below this bound.
- Empty sides. A call whose range of is empty returns at once after the swap. If all ids of are less than , each left child gets an empty range of , so only a chain of about calls does work, at about tests each.
- Space. The recursion depth is , because the smaller range halves at each level. The output has at most ids.
- Time. Linear in the number of tests, on the word RAM with random access to both lists.
Properties
- Adaptive to the ratio. The same code costs for equal lengths and for a very short list, with no parameter to tune.
- Random access. The binary search jumps to the middle of a range, so the lists must support access by index. On compressed lists this needs a block index or a code such as Elias-Fano encoding.
- Output in order. With line L6 between the two calls, comes out sorted.
- Recursive. It suits a parallel run: the two calls of lines L5 and L7 work on disjoint ranges.
Variants and improvements
- More than two lists. Intersect the two shortest lists, then the result with the next one, and so on. Barbay et al. describe the -list form this way, with a sort of the result at the end, which is needed if the middle id is output before the left call.
- Galloping in place of binary search. Line L4 can gallop from one end of the range; this changes the constants only.
- Stop when both sides are small. When both ranges hold only a few ids, a merge of the two ranges avoids the cost of more calls. This changes the constant factor, not the bound.
- Hwang and Lin merging. The merge of Hwang and Lin also uses binary search in blocks of the longer list, see sorted array intersection.
When to use it
Use it for two lists in memory with random access, when the ratio of their lengths is not known in advance: it adapts with no tuning. For many lists, or for lists that can only be read in order, small-versus-small with a block index or the adaptive algorithm of Demaine, López-Ortiz and Munro are the usual choices.
Pitfalls
- The median from the long list. Line L1 must take the median from the smaller range. Without the swap, a call with and splits the long list and makes a binary search for each of up to ids, which is no better than the merge.
- The whole list in the search. Line L4 must search only . A search over all of is still correct, but costs about in each call, and the bound becomes .
- The order of output. Line L6 must come after the call of line L5 and before the call of line L7. If line L6 comes first, the result is the right set but not in increasing order, and the next intersection step, which needs a sorted list, gives wrong results.
- Skipping the matched id. After a match, line L6 sets . Without it, the right call still works, because all ids of are greater than , but its range has one more id to search.
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
# Part of https://algorithm.tamnd.com/baeza-yates-intersection/. The authors are listed in prov/SRAJ81.jsonl.
from typing import Any, Sequence
def _lower_bound(b: Sequence[Any], x: Any, lo: int, hi: int) -> int:
"""Least p in [lo, hi] with p == hi or b[p] >= x, for sorted b. At most ceil(log2(hi - lo + 1)) tests."""
while lo < hi:
q = (lo + hi) // 2
if b[q] < x:
lo = q + 1
else:
hi = q
return lo
def _by(a: Sequence[Any], alo: int, ahi: int, b: Sequence[Any], blo: int, bhi: int, out: list[Any]) -> None:
if ahi - alo > bhi - blo: # @line L1
a, alo, ahi, b, blo, bhi = b, blo, bhi, a, alo, ahi
if alo == ahi: # @line L2
return
mid = alo + (ahi - alo) // 2 # @line L3
x = a[mid]
p = _lower_bound(b, x, blo, bhi) # @line L4
_by(a, alo, mid, b, blo, p, out) # @line L5
if p < bhi and b[p] == x: # @line L6
out.append(x)
p += 1
_by(a, mid + 1, ahi, b, p, bhi, out) # @line L7
def baeza_yates(a: Sequence[Any], b: Sequence[Any]) -> list[Any]:
"""Return the ids in both a and b, in increasing order (Baeza-Yates double binary search).
Precondition: a and b are strictly increasing. With m = min(len(a), len(b)) >= 1 and
n = max(len(a), len(b)), it makes at most 2 m log2(2 + n/m) + 6 m tests (< and ==).
Extra space O(log m) for the recursion, besides the output.
"""
out: list[Any] = []
_by(a, 0, len(a), b, 0, len(b), out)
return out
def baeza_yates_all(lists: Sequence[Sequence[Any]]) -> list[Any]:
"""Intersect k >= 1 strictly increasing lists two at a time, shortest first."""
order = sorted(lists, key=len)
r = list(order[0])
for t in range(1, len(order)):
if not r:
break
r = baeza_yates(r, order[t])
return r
irtoy.py 76 lines
# 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
test_baeza_yates_intersection.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/baeza-yates-intersection/. The authors are listed in prov/SRAJ81.jsonl.
import math
import random
import irtoy
from baeza_yates_intersection import baeza_yates, baeza_yates_all
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(a: list[int], b: list[int]) -> tuple[list[int], int]:
c = Counter()
r = baeza_yates([Key(x, c) for x in a], [Key(x, c) for x in b])
return [k.v for k in r], c.n
def bound(la: int, lb: int) -> float:
m, n = min(la, lb), max(la, lb)
if m == 0:
return 0.0
return 2 * m * math.log2(2 + n / m) + 6 * m
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(a, b)
assert r == [20, 40]
assert n == 13
r2, n2 = counted(b, a)
assert r2 == [20, 40] and n2 == n
ix = postings()
assert baeza_yates_all([ix["sorted"], ix["array"], ix["search"]]) == [1]
r, n = counted(ix["sorted"], ix["array"])
assert r == [1, 2, 8]
def test_irtoy_all_pairs() -> None:
ix = postings()
terms = sorted(ix)
for i, s in enumerate(terms):
for t in terms[i + 1:]:
r, n = counted(ix[s], ix[t])
assert r == sorted(set(ix[s]) & set(ix[t]))
assert n <= bound(len(ix[s]), len(ix[t])) + 1e-9
for q in irtoy.QUERIES.values():
lists = [ix.get(t, []) for t in irtoy.tokenize(q)]
assert baeza_yates_all(lists) == sorted(set(lists[0]).intersection(*lists[1:]))
def test_edges() -> None:
assert baeza_yates([], []) == []
assert baeza_yates([1], []) == []
assert baeza_yates([], [1, 2]) == []
assert baeza_yates([4], [4]) == [4]
assert baeza_yates([1, 2, 3], [1, 2, 3]) == [1, 2, 3]
assert baeza_yates([1, 3, 5], [2, 4, 6]) == []
assert baeza_yates_all([[2, 5]]) == [2, 5]
def test_random_against_sets() -> None:
rng = random.Random(2004)
for _ in range(1500):
u = rng.choice([20, 300, 100000])
a = sorted(rng.sample(range(u), rng.randint(0, min(u, rng.choice([3, 30, 200])))))
b = sorted(rng.sample(range(u), rng.randint(0, min(u, rng.choice([3, 30, 2000])))))
r, n = counted(a, b)
assert r == sorted(set(a) & set(b))
assert n <= bound(len(a), len(b)) + 1e-9
if a and b:
assert n <= 10 * math.log2(math.comb(len(a) + len(b), min(len(a), len(b))))
for _ in range(300):
lists = [sorted(rng.sample(range(100), rng.randint(0, 50))) for _ in range(rng.randint(1, 5))]
assert baeza_yates_all(lists) == sorted(set(lists[0]).intersection(*lists[1:]))
History
Ricardo Baeza-Yates presented the algorithm at the CPM conference in 2004, with an analysis of its worst case as a function of the two lengths. Baeza-Yates and Salinger studied it in experiments in 2005. Barbay, López-Ortiz, Lu and Salinger compared it in 2009 with SvS and with the adaptive algorithms of Demaine, López-Ortiz and Munro and of Barbay and Kenyon on a log of web queries.
References
- Ricardo Baeza-Yates, A fast set intersection algorithm for sorted sequences, Combinatorial Pattern Matching (CPM 2004), Lecture Notes in Computer Science 3109, Springer, 400-408, the algorithm (binary search of the median of the smaller sequence in the larger one, then recursion on both sides) and its worst case analysis as a function of the two lengths
- Ricardo Baeza-Yates and Alejandro Salinger, Experimental analysis of a fast intersection algorithm for sorted sequences, String Processing and Information Retrieval (SPIRE 2005), Lecture Notes in Computer Science, Springer, 13-24, the experiments that compare the algorithm with the merge and with the adaptive algorithms, and its use for more than two sequences
- 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 the Baeza-Yates algorithm for k sets, two at a time from the smallest, and its comparison with SvS and the adaptive algorithms on web queries
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 SRAJ81 Edit this page History Report an error Markdown