Algorithm Search⌘K

Algorithmresearch

Demaine-Lopez-Ortiz-Munro adaptive intersection

Also called adaptive set intersection.

Intersects k sorted sets by cycling through them with galloping search, in time bounded by the size of a proof of the result.

Time
Ω(m log(n/m + 1)) lowerO(m log(n/m + 1)) two_lists
Space
O(k) extra
Where
k = the number of lists; m = the length of the shorter of two lists; n = the length of the longer of two lists
Properties
comparison baseddeterministiciterative

The adaptive intersection of Erik Demaine, Alejandro López-Ortiz and Ian Munro intersects kk sorted lists by keeping one candidate id, the eliminator, and searching for it in the lists in turn with galloping steps. A list that holds an id greater than the eliminator gives a new eliminator; when all lists hold it, it goes to the output. The cost depends on how the lists interleave, not only on their lengths: an input whose result has a short proof is fast. The paper of 2000 gallops in each set from both ends and proves at most 8kG8kG comparisons, where GG is the gap cost of the shortest proof of the result. This page gives the simpler form that gallops forward only. For two lists of lengths m≤nm \le n, it makes at most 2mlog⁡2(1+n/m)+6m2m \log_2(1 + n/m) + 6m tests, which is at most 8 times the lower bound log⁡2(m+nm)\log_2 \binom{m+n}{m} of every algorithm in the comparison model. The proof of that lower bound is on this page, and the merge, small-versus-small and Baeza-Yates pages use it.

In plain words

Pick the first number of the shortest list as the candidate. Go to the next list and jump forward in it, by steps that double, until you pass the candidate. Then search back in the last jump to find the first number that is not smaller than the candidate.

If that number is the candidate, this list agrees, and you go on to the next list. If it is larger, it is the new candidate, and the other lists must check it again. When every list agrees, the candidate is in the answer, and the next number of the last list becomes the new candidate.

Each list keeps its own place and never moves back. When the lists have long runs with no common numbers, the doubling jumps cross a run at a cost that grows only with the number of digits of its length.

The problem

The input is k≥1k \ge 1 lists of document ids, each strictly increasing. The output is the list of ids that are in all of them, in increasing order. It is the AND query of posting list intersection.

The algorithm

HH is the set of lists that are known to hold the eliminator ee, and ℓ\ell is the list of the last search. Each list ss has an index pos(s)pos(s), below which all of its ids are already dealt with, and a step jump(s)jump(s).

  1. ADAPTIVE(L_0, ..., L_{k-1}) ▷ each list strictly increasing
  2. 1sort the lists by length, shortest first; if a list is empty then return ()
  3. 2e ← L_0[0], pos(0) ← 1, H ← {0}, ℓ ← 0; pos(s) ← 0, jump(s) ← 1 for each other s
  4. 3loop
  5. 4if |H| = k then ▷ all lists hold e
  6. 5append e to R
  7. 6if pos(ℓ) = |L_ℓ| then return R
  8. 7e ← L_ℓ[pos(ℓ)], pos(ℓ) ← pos(ℓ) + 1, H ← {ℓ}, and go to L4
  9. 8s ← the next list after s, in round robin, that is not in H
  10. 9if pos(s) = |L_s| then return R
  11. 10p ← min(pos(s) + jump(s) - 1, |L_s| - 1)
  12. 11if L_s[p] < e then ▷ one doubling step
  13. 12if p = |L_s| - 1 then return R
  14. 13pos(s) ← p + 1, jump(s) ← 2 jump(s)
  15. else ▷ e lies in L_s[pos(s)..p]
  16. 14a ← pos(s), c ← p
  17. 15while a < c: q ← ⌊(a + c)/2⌋; if L_s[q] < e then a ← q + 1 else c ← q
  18. 16pos(s) ← a + 1, jump(s) ← 1, ℓ ← s
  19. 17if L_s[a] = e then H ← H ∪ {s}
  20. 18else e ← L_s[a], H ← {s}

Each pass of lines L8 to L18 makes one doubling step in one list, so with k≥3k \ge 3 the lists that are not in HH take turns, one step each. A run of a list is its sequence of steps from jump=1jump = 1 to the next search. The stops at lines L9 and L12 mean that one list has no id at least ee, so no more ids can be common.

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, with B[i]=2i+2B[i] = 2i + 2. AA is shorter, so it is L0L_0, and the first eliminator is 7.

run eliminator probes of line L11 search of line L15 line L17 tests result
BB, 1 7 B[0]=2B[0] = 2, B[2]=6B[2] = 6, B[6]=14B[6] = 14 B[4]=10B[4] = 10, B[3]=8B[3] = 8 8≠78 \ne 7 6 e=8e = 8
AA, 1 8 A[1]=20A[1] = 20 none 20≠820 \ne 8 2 e=20e = 20
BB, 2 20 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 20=2020 = 20 6 output 20, e=B[10]=22e = B[10] = 22
AA, 2 22 A[2]=40A[2] = 40 none 40≠2240 \ne 22 2 e=40e = 40
BB, 3 40 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 40=4040 = 40 6 output 40, then stop at line L6

The result is (20,40)(20, 40) after 22 tests. The bound of Theorem 2 below is 2⋅3log⁡2(1+20/3)+18≈35.62 \cdot 3 \log_2(1 + 20/3) + 18 \approx 35.6. On this input, Baeza-Yates makes 13 tests and small-versus-small makes 19, because each new eliminator from AA starts a new run in BB with a step of 1.

On the toy collection, sorted AND array AND search sorts the lists to search (1,7)(1, 7), array (1,2,8)(1, 2, 8) and sorted (1,2,4,8)(1, 2, 4, 8), and returns document 1 after 12 tests. Posting AND list returns (3,4)(3, 4) after 4 tests. For 10 random ids and 10000 random ids below 10610^6, it made 211 tests, against the bound of about 259.3 and the lower bound of about 111.1.

Correctness

The proof keeps four facts before each check of line L4. The output is strictly increasing and holds only common ids, all less than ee. Every common id not yet in the output is at least ee. In a list not in HH, every id below pos(s)pos(s) is less than ee. In a list in HH, the id just below pos(s)pos(s) is ee, and the ones before it are less. A doubling step keeps these facts because the list is sorted. A search finds the first id at least ee, so either the list joins HH or its id becomes a larger eliminator, and no common id lies between the old and the new eliminator. The sum of the indices grows at each pass, so the loop stops, and each stop happens only when no common id at least ee is left. The full proof is in the proof file below.

Proof: The adaptive intersection is correct and within a constant factor of the log2 C(m+n, m) lower boundfull

The input is k≥1k \ge 1 lists L0,…,Lk−1L_0, \ldots, L_{k-1}, each strictly increasing, sorted so that n0≤n1≤⋯≤nk−1n_0 \le n_1 \le \cdots \le n_{k-1}, where ns=∣Ls∣n_s = |L_s|. A test is one two-way comparison of ids, << or ==. The line numbers are those of the main block of the page. If a list is empty, the algorithm returns the empty list with no test, which is correct, so from here each ns≥1n_s \ge 1. The state is the eliminator ee, the set HH of lists that are known to hold ee (the set held), and for each list ss the index pos(s)pos(s) and the step jump(s)jump(s).

Invariant. Before each check of line L4:

  • (I1) the output is strictly increasing, each output id is common to all lists, and each output id is less than ee;
  • (I2) each common id that is not in the output is at least ee;
  • (I3) for each list s∉Hs \notin H, every id of LsL_s at an index below pos(s)pos(s) is less than ee;
  • (I4) for each list s∈Hs \in H, Ls[pos(s)−1]=eL_s[pos(s) - 1] = e, and every id of LsL_s at a lower index is less than ee.

Lemma 1. The invariant holds at the start and after each pass of the loop.

Proof. At the start, e=L0[0]e = L_0[0], pos(0)=1pos(0) = 1, H={0}H = \{0\} and pos(s)=0pos(s) = 0 for s≠0s \ne 0. (I1) holds with an empty output, (I3) holds with no ids below index 0, and (I4) holds for list 0. A common id is in L0L_0, so it is at least L0[0]=eL_0[0] = e, which is (I2).

Lines L5 to L7. When HH holds all kk lists, (I4) says that ee is in each list, so ee is common. By (I1) it is greater than the ids already in the output, so the output stays strictly increasing after line L5. Let ℓ\ell be the list of the last search. If pos(ℓ)<nℓpos(\ell) < n_\ell, line L7 sets e′=Lℓ[pos(ℓ)]e' = L_\ell[pos(\ell)], the next id of LℓL_\ell after ee, so e′>ee' > e. (I1) holds because the new output id ee is less than e′e'. A common id that is not in the output is at least ee by (I2), is not ee, and is in LℓL_\ell, so it is at least e′e', which is (I2). (I4) holds for ℓ\ell after pos(ℓ)pos(\ell) grows by one. For each other list, the ids below pos(s)pos(s) are at most e<e′e < e', which is (I3), because HH is now {ℓ}\{\ell\}.

Lines L10 to L13. A step on a list s∉Hs \notin H probes p≥pos(s)p \ge pos(s). If Ls[p]<eL_s[p] < e, every id of LsL_s up to index pp is less than ee, so (I3) holds after pos(s)←p+1pos(s) \leftarrow p + 1. Nothing else changes.

Lines L14 to L18. If Ls[p]≥eL_s[p] \ge e, the binary search on [pos(s),p][pos(s), p] uses Ls[p]≥eL_s[p] \ge e and (I3), so it returns the least index aa with Ls[a]≥eL_s[a] \ge e (Lemma 2 of the proof file of the posting list page). Then pos(s)=a+1pos(s) = a + 1. If Ls[a]=eL_s[a] = e, list ss joins HH and (I4) holds for it. Else e′=Ls[a]>ee' = L_s[a] > e and H={s}H = \{s\}. (I4) holds for ss. For each other list, the ids below its index are at most e<e′e < e' by (I3) and (I4), so (I3) holds for it. A common id not in the output is at least ee by (I2), and it is in LsL_s, so it is at least Ls[a]=e′L_s[a] = e', which is (I2). (I1) holds because e′>ee' > e. □\square

Theorem 1 (correctness). The algorithm stops, and it returns the ids common to all lists, in increasing order.

Proof. Each pass either stops or increases ∑spos(s)\sum_s pos(s): line L7 adds one to pos(ℓ)pos(\ell), line L13 sets pos(s)=p+1pos(s) = p + 1 with p≥pos(s)p \ge pos(s), and line L16 sets pos(s)=a+1pos(s) = a + 1 with a≥pos(s)a \ge pos(s). This sum is at most ∑sns\sum_s n_s, so the loop stops. It stops at one of three lines.

  • Line L6: the common id ee was output, and the list ℓ\ell has no id after ee, so no common id is greater than ee.
  • Line L9: pos(s)=nspos(s) = n_s for a list s∉Hs \notin H, so by (I3) every id of LsL_s is less than ee.
  • Line L12: Ls[ns−1]<eL_s[n_s - 1] < e, so every id of LsL_s is less than ee.

In the last two cases, no common id is at least ee. In all three cases, (I2) says that each common id is in the output, and (I1) says that the output holds only common ids, in increasing order. ■\blacksquare

The count of tests

A run of list ss is a maximal sequence of steps of lines L10 and L11 on ss that starts with jump(s)=1jump(s) = 1. A run ends with a binary search (lines L14 to L18), with the stop of line L12, or when the algorithm stops at another line. Let rsr_s be the number of runs of list ss; the code counts it. Let PP be the value of pos(s)pos(s) at the start of a run, and let its span cc be ns−Pn_s - P if the run ends at line L12, and the value of pos(s)pos(s) at its end minus PP in the other cases.

Lemma 2 (one run). A run with span cc has c≥1c \ge 1 and makes at most 2log⁡2c+22 \log_2 c + 2 tests.

Proof. Step ii of the run, for i=0,1,…i = 0, 1, \ldots, starts with pos(s)=P+2i−1pos(s) = P + 2^i - 1 and jump(s)=2ijump(s) = 2^i, and probes p=min⁡(P+2i+1−2,ns−1)p = \min(P + 2^{i+1} - 2, n_s - 1). Let the run make tt steps with the result "less than", then one more step.

  • If the last step has the result "not less", the binary search runs on [pos(s),p][pos(s), p], a range of at most 2t2^t indices whose last index is known to hold an id at least ee. It makes at most tt tests, because each test halves this range. Line L17 makes one more test. The total is at most (t+1)+t+1=2t+2(t + 1) + t + 1 = 2t + 2. The new index is a+1≥P+2ta + 1 \ge P + 2^t, so c≥2tc \ge 2^t and t≤log⁡2ct \le \log_2 c.
  • If the last step stops at line L12, the run made t+1t + 1 tests, and p=ns−1≥P+2t−1p = n_s - 1 \ge P + 2^t - 1, so c≥2tc \ge 2^t, and t+1≤2log⁡2c+2t + 1 \le 2 \log_2 c + 2.
  • If the algorithm stops on another list after t≥1t \ge 1 steps of this run, the run made tt tests and c=2t−1≥2t−1c = 2^t - 1 \ge 2^{t-1}, so t≤2(t−1)+2≤2log⁡2c+2t \le 2(t - 1) + 2 \le 2 \log_2 c + 2.

In each case c≥1c \ge 1. □\square

Lemma 3 (one list). List ss makes at most 2rslog⁡2(1+ns/rs)+2rs2 r_s \log_2(1 + n_s / r_s) + 2 r_s tests, or none if rs=0r_s = 0.

Proof. Each test is made in a run of the list that makes it. The index pos(s)pos(s) never goes down and a run starts at the current index, so the spans of the runs of ss cover disjoint ranges of indices, and their sum is at most nsn_s. By Lemma 2 and Jensen's inequality for the concave function log⁡2\log_2, the runs make at most ∑j(2log⁡2cj+2)≤2rslog⁡2(ns/rs)+2rs\sum_j (2 \log_2 c_j + 2) \le 2 r_s \log_2(n_s / r_s) + 2 r_s tests, which is at most the bound. □\square

Lemma 4. Let EE be the number of values that ee takes. Then rs≤Er_s \le E for each list ss.

Proof. A run of ss starts only when s∉Hs \notin H. A run that does not end the algorithm ends at line L17 or L18 with s∈Hs \in H, and ss leaves HH only when ee changes, at line L7 or line L18. So two runs of ss start under two different values of ee. □\square

With Lemma 4 and the fact that h(t)=tlog⁡2(1+c/t)h(t) = t \log_2(1 + c/t) is nondecreasing in t>0t > 0 for each c≥0c \ge 0, the total number of tests is at most ∑s(2Elog⁡2(1+ns/E)+2E)\sum_s (2E \log_2(1 + n_s / E) + 2E). Each value of ee is an id of the input, and the values increase, so EE is at most the number of distinct ids. On inputs with a short proof of the result, EE is small.

Theorem 2 (two lists). For k=2k = 2 with m=n0≤n=n1m = n_0 \le n = n_1, the algorithm makes at most

2mlog⁡2(1+nm)+6m  ≤  8log⁡2(m+nm)2m \log_2\left(1 + \frac{n}{m}\right) + 6m \;\le\; 8 \log_2 \binom{m+n}{m}

tests.

Proof. When k=2k = 2 and HH is not full, HH holds one list and each step is on the other one. A run of list ss ends with s∈Hs \in H, and if line L7 follows, HH becomes {s}\{s\} again. So the runs of the two lists alternate, and the first run is a run of list 1. This gives r1≤r0+1r_1 \le r_0 + 1. Each run of list 0 has span at least 1 by Lemma 2, the spans are disjoint, and none of them holds index 0, which line L2 takes with no test. So r0≤m−1r_0 \le m - 1 and r1≤mr_1 \le m. By Lemma 3 and the monotone function hh, list 0 makes at most 2mlog⁡22+2m=4m2m \log_2 2 + 2m = 4m tests and list 1 makes at most 2mlog⁡2(1+n/m)+2m2m \log_2(1 + n/m) + 2m tests. For the second form, (m+nm)=∏i=1mn+ii≥(1+n/m)m\binom{m+n}{m} = \prod_{i=1}^{m} \frac{n+i}{i} \ge (1 + n/m)^m, so 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, because n≥mn \ge m. ■\blacksquare

The lower bound

The comparison model: an algorithm sees the ids only through comparisons of two input ids, with the outcomes <<, == and >> (a two-way test gives less information). For fixed lengths, the algorithm is a decision tree, and each leaf fixes the output as a set of positions of AA.

Lemma 5 (adjacent pairs). Let the input be two lists AA and BB with all ids distinct, so that A∩BA \cap B is empty. In the merged order of all m+nm + n ids, let xx and yy be adjacent and in different lists. Then every correct algorithm compares xx with yy on this input.

Proof. Say xx is in AA, yy is in BB and x<yx < y; the other cases are the same. Suppose the algorithm does not compare xx with yy. Change the input by giving yy the value of xx. The list BB stays strictly increasing: the id of BB before yy is less than yy, is not xx, and no id lies between xx and yy, so it is less than xx. Each comparison of yy with an id z≠xz \ne x has the same outcome as before, because no id lies strictly between xx and yy, and z≠xz \ne x. Comparisons that do not involve yy do not change. So the new input follows the same path to the same leaf, and the algorithm gives the same output, the empty set. But on the new input, xx is common to both lists. This is a contradiction. □\square

Theorem 3 (lower bound). Every algorithm in the comparison model that intersects two sorted lists of lengths mm and nn makes at least ⌈log⁡2(m+nm)⌉\lceil \log_2 \binom{m+n}{m} \rceil comparisons on some input.

Proof. Take the (m+nm)\binom{m+n}{m} inputs made from the ids 1,…,m+n1, \ldots, m+n, one for each choice of the mm ids that go to AA; BB gets the rest. Let such an input reach the leaf vv. By Lemma 5, the path to vv holds the outcome of each comparison of two adjacent ids from different lists, and the order of two adjacent ids from the same list is known in advance. So the outcomes on the path, with the order inside each list, fix the whole merged order, and with it the choice of the mm ids of AA. So the (m+nm)\binom{m+n}{m} inputs reach different leaves. On these inputs no comparison has the outcome ==, so each node on their paths has at most two children that they use. A binary tree with at least (m+nm)\binom{m+n}{m} leaves has depth at least log⁡2(m+nm)\log_2 \binom{m+n}{m}, and depth is an integer. ■\blacksquare

Corollary 4 (equal lengths). For m=nm = n, every correct algorithm makes at least 2n−12n - 1 comparisons on the input a1<b1<a2<b2<⋯<an<bna_1 < b_1 < a_2 < b_2 < \cdots < a_n < b_n, because all 2n−12n - 1 adjacent pairs of the merged order are in different lists (Lemma 5). The merge makes at most 2n−12n - 1 three-way steps, so it is exactly optimal in this count. □\square

Remark. Lemma 5 is the reason that the cost of an adaptive algorithm can depend on the input and not only on the lengths. On a given input, the comparisons that a correct algorithm must make form a certificate of the result. When the two lists interleave in few blocks, this certificate is short, and the galloping steps of the algorithm find each block boundary at a cost that is logarithmic in the block length. Theorem 3 bounds the worst case over all inputs of the given lengths, and Theorem 2 shows that the algorithm meets it up to a factor of 8.

Complexity

  • One run. A run that moves the index of its list by cc makes at most 2log⁡2c+22 \log_2 c + 2 tests: t+1t + 1 doubling probes, at most tt tests of the binary search, and one equality test, with c≥2tc \ge 2^t.
  • One list. The runs of a list cover disjoint parts of it, so by Jensen's inequality a list of length nsn_s with rsr_s runs makes at most 2rslog⁡2(1+ns/rs)+2rs2 r_s \log_2(1 + n_s / r_s) + 2 r_s tests. Two runs of a list start under two different eliminators, so rs≤Er_s \le E, the number of values of ee.
  • Two lists. For k=2k = 2 the runs alternate between the lists, so the longer list has at most mm runs and the shorter one at most m−1m - 1. This gives at most 2mlog⁡2(1+n/m)+6m≤8log⁡2(m+nm)2m \log_2(1 + n/m) + 6m \le 8 \log_2 \binom{m+n}{m} tests.
  • Lower bound. Every comparison algorithm needs ⌈log⁡2(m+nm)⌉\lceil \log_2 \binom{m+n}{m} \rceil comparisons in the worst case, and 2n−12n - 1 when m=nm = n. The proof: on an input with no common id, an algorithm must compare each two ids that are next to each other in the merged order and come from different lists; if it skips one pair, making the two ids equal does not change any outcome, but it changes the answer. So the outcomes at a leaf of the decision tree fix the interleaving of the two lists, and the (m+nm)\binom{m+n}{m} interleavings need that many leaves.
  • The paper. With galloping from both ends, Demaine, López-Ortiz and Munro prove O(kG)O(kG) time and at most 8kG8kG comparisons (Theorem 5.1 and Corollary 5.2), where GG is the gap cost of the shortest proof of the result. This page does not prove that bound for the one-sided form.
  • Time and space. The code finds the next list not in HH by a scan, which costs O(k)O(k) per step; a circular list of the lists not in HH makes it O(1)O(1). The extra space is O(k)O(k) for the indices and steps.

Properties

  • Adaptive. The cost follows the structure of the input. Two lists that interleave in a few long blocks cost a few galloping runs, whatever their lengths.
  • Forward only. Each index only grows, so the galloping step can be replaced by any forward seek to the first id at least ee, such as one on a posting list with skip pointers or a block index. The bounds of this page are for galloping on arrays.
  • No list is special. After the first eliminator, the order of the lists does not matter for correctness. The sort by length only gives the first eliminator from the shortest list.
  • Output in order. The ids come out in increasing order, so the result can be piped into the next query step.

Variants and improvements

  • Galloping from both ends. The algorithm of the paper also searches each set from its far end, so that the cost of the largest gap in a set is not paid in full. This is the form that the 8kG8kG bound is for.
  • Sequential. Barbay and Kenyon search the eliminator in one list until it is found or passed, then go to the next list in a cycle, in place of one doubling step per list. For two lists, the form of this page also searches one list at a time.
  • Small Adaptive. Barbay, López-Ortiz, Lu and Salinger study this variant next to small-versus-small and the adaptive methods in their experiments on web queries.
  • Joins. The leapfrog join in leapfrog triejoin uses the same pattern for kk sorted iterators with a seek: the largest current key is the target, and the other iterators seek to it in turn.

When to use it

Use it for AND queries of three or more terms, or when the lists may interleave in long blocks, for example when the documents of one topic have nearby ids. For two lists that differ a lot in length, small-versus-small or Baeza-Yates have the same bound with less bookkeeping. For two lists of about the same length that interleave finely, the merge makes fewer tests.

Pitfalls

  • Galloping from the start of the list. Each run must start at pos(s)pos(s), not at index 0. A restart costs about log⁡2n\log_2 n per search and loses the adaptive bound.
  • Not resetting the step. Line L16 must set jump(s)←1jump(s) \leftarrow 1. If the step keeps its large value, the next run starts with a long jump and a long binary search, even when the next id is close.
  • Output too early. An id is common only when all kk lists hold it. Output at line L5 only when HH has all kk lists, and remove the other lists from HH at each new eliminator, at line L7 and line L18.
  • Repeated ids. The proof needs each list to be strictly increasing. A list with a repeated id can make the equality test of line L17 see the same id twice.
  • One list. With k=1k = 1, HH is full at the start. Line L7 must go back to line L4, else the round robin of line L8 finds no list to step on.

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.

adaptive_set_intersection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-set-intersection/. The authors are listed in prov/340HGS.jsonl.

from typing import Any, Sequence


def adaptive_intersect(lists: Sequence[Sequence[Any]], stats: dict[str, Any] | None = None) -> list[Any]:
    """Return the ids that are in each list, in increasing order.

    The one-sided form of the adaptive algorithm of Demaine, Lopez-Ortiz and Munro:
    one eliminator e, and one doubling step at a time in each list that is not yet
    known to hold e, in round robin. Precondition: at least one list, each strictly
    increasing. Only the tests < and == are used. A list s with r_s galloping runs
    makes at most 2 r_s log2(1 + n_s / r_s) + 2 r_s tests.

    If stats is a dict, it receives "runs" (the number of runs in each list, in the
    sorted order), "lengths" (the sorted lengths) and "eliminators" (how many times e
    was set).
    """
    order = sorted(lists, key=len)  # @line L1
    k = len(order)
    runs = [0] * k
    elims = 0
    out: list[Any] = []
    if all(len(lst) > 0 for lst in order):
        pos = [0] * k
        jump = [1] * k
        e = order[0][0]  # @line L2
        elims = 1
        pos[0] = 1
        held = {0}
        last = 0
        s = 0
        while True:  # @line L3
            if len(held) == k:  # @line L4
                out.append(e)  # @line L5
                if pos[last] == len(order[last]):  # @line L6
                    break
                e = order[last][pos[last]]  # @line L7
                elims += 1
                pos[last] += 1
                held = {last}
                continue
            s = (s + 1) % k  # @line L8
            while s in held:
                s = (s + 1) % k
            lst = order[s]
            n = len(lst)
            if pos[s] == n:  # @line L9
                break
            if jump[s] == 1:
                runs[s] += 1
            p = min(pos[s] + jump[s] - 1, n - 1)  # @line L10
            if lst[p] < e:  # @line L11
                if p == n - 1:  # @line L12
                    break
                pos[s] = p + 1  # @line L13
                jump[s] *= 2
            else:
                a, c = pos[s], p  # @line L14
                while a < c:  # @line L15
                    q = (a + c) // 2
                    if lst[q] < e:
                        a = q + 1
                    else:
                        c = q
                pos[s] = a + 1  # @line L16
                jump[s] = 1
                last = s
                if lst[a] == e:  # @line L17
                    held.add(s)
                else:
                    e = lst[a]  # @line L18
                    elims += 1
                    held = {s}
    if stats is not None:
        stats["runs"] = runs
        stats["lengths"] = [len(lst) for lst in order]
        stats["eliminators"] = elims
    return out
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_adaptive_set_intersection.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-set-intersection/. The authors are listed in prov/340HGS.jsonl.

import math
import random
from typing import Any

import irtoy
from adaptive_set_intersection import adaptive_intersect


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, dict[str, Any]]:
    c = Counter()
    stats: dict[str, Any] = {}
    r = adaptive_intersect([[Key(x, c) for x in lst] for lst in lists], stats)
    return [k.v for k in r], c.n, stats


def run_bound(stats: dict[str, Any]) -> float:
    """The bound of the proof: 2 r log2(1 + n / r) + 2 r for each list."""
    total = 0.0
    for r, n in zip(stats["runs"], stats["lengths"]):
        if r > 0:
            total += 2 * r * math.log2(1 + n / r) + 2 * r
    return total


def two_list_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(1 + 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 check(lists: list[list[int]]) -> int:
    r, n, stats = counted(lists)
    expect = sorted(set(lists[0]).intersection(*lists[1:]))
    assert r == expect
    assert n <= run_bound(stats) + 1e-9
    if all(lists):
        assert all(x <= stats["eliminators"] for x in stats["runs"])
    if len(lists) == 2:
        assert n <= two_list_bound(len(lists[0]), len(lists[1])) + 1e-9
        if all(lists):
            m = min(len(lists[0]), len(lists[1]))
            assert n <= 8 * math.log2(math.comb(len(lists[0]) + len(lists[1]), m))
    return n


def test_example() -> None:
    a = [7, 20, 40]
    b = list(range(2, 41, 2))
    r, n, stats = counted([b, a])
    assert r == [20, 40]
    assert n == 22
    assert stats["runs"] == [2, 3]
    assert stats["eliminators"] == 5
    ix = postings()
    r, n, stats = counted([ix["sorted"], ix["array"], ix["search"]])
    assert r == [1]
    r, n, stats = counted([ix["posting"], ix["list"]])
    assert r == [3, 4]


def test_irtoy() -> None:
    ix = postings()
    terms = sorted(ix)
    for i, s in enumerate(terms):
        for t in terms[i + 1:]:
            check([ix[s], ix[t]])
    for q in irtoy.QUERIES.values():
        check([ix.get(t, []) for t in irtoy.tokenize(q)])
    rng = random.Random(35)
    for _ in range(300):
        check([ix[t] for t in rng.sample(terms, rng.randint(1, 5))])


def test_edges() -> None:
    assert adaptive_intersect([[]]) == []
    assert adaptive_intersect([[3, 9]]) == [3, 9]
    assert adaptive_intersect([[1, 2], []]) == []
    assert adaptive_intersect([[4], [4], [4]]) == [4]
    assert adaptive_intersect([[1, 2, 3], [1, 2, 3]]) == [1, 2, 3]
    assert adaptive_intersect([[1, 3, 5], [2, 4, 6]]) == []
    assert adaptive_intersect([[1, 2, 3], [4, 5, 6], [1, 6]]) == []
    assert adaptive_intersect([[10], list(range(100))]) == [10]


def test_random_against_sets() -> None:
    rng = random.Random(2000)
    for _ in range(1200):
        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])))))
        check([a, b])
    for _ in range(500):
        u = rng.choice([30, 200, 5000])
        k = rng.randint(1, 6)
        lists = [sorted(rng.sample(range(u), rng.randint(0, min(u, rng.choice([5, 50, 500]))))) for _ in range(k)]
        check(lists)


def test_lower_bound_inputs() -> None:
    """Two disjoint lists that interleave in blocks; the count stays within 8 log2 C(m+n, m)."""
    rng = random.Random(743)
    for _ in range(200):
        m = rng.randint(1, 40)
        n = rng.randint(m, 2000)
        values = list(range(m + n))
        chosen = set(rng.sample(values, m))
        a = [v for v in values if v in chosen]
        b = [v for v in values if v not in chosen]
        assert check([a, b]) >= 1

History

Demaine, López-Ortiz and Munro defined the proof of a result of a set operation and its gap cost, and gave the adaptive algorithms for intersection, union and difference at SODA in 2000. They reported experiments with the intersection algorithm for text retrieval at ALENEX in 2001. Barbay and Kenyon gave the Sequential algorithm and its analysis at SODA in 2002, with a journal version in 2008. Barbay, López-Ortiz, Lu and Salinger compared these algorithms with small-versus-small and Baeza-Yates on a log of web queries in 2009.

References

  1. Erik D. Demaine, Alejandro López-Ortiz and J. Ian Munro, Adaptive set intersections, unions, and differences, Proceedings of the 11th ACM-SIAM Symposium on Discrete Algorithms (SODA 2000), 743-752, Section 3 (proofs of the result, and their gap cost), Section 5 (the intersection algorithm with an eliminator and galloping from both ends), Theorem 5.1 and Corollary 5.2 (O(kG) time and at most 8kG comparisons)
  2. Erik D. Demaine, Alejandro López-Ortiz and J. Ian Munro, Experiments on adaptive set intersections for text retrieval systems, Algorithm Engineering and Experimentation (ALENEX 2001), Lecture Notes in Computer Science 2153, Springer, 91-104, the experiments with the adaptive intersection algorithm for text retrieval
  3. Jérémy Barbay and Claire Kenyon, Adaptive intersection and t-threshold problems, Proceedings of the 13th ACM-SIAM Symposium on Discrete Algorithms (SODA 2002), 390-399; journal version in ACM Transactions on Algorithms 4(1), Article 4, 2008, the Sequential algorithm, which searches the eliminator in one set after another, and its analysis
  4. 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 Adaptive, Small Adaptive, Sequential, SvS and Baeza-Yates, and their comparison on web query logs

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.lower
  • a full proof of time.two_lists
  • 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