Algorithm Search⌘K

Algorithmcore

Most popular completion

Also called popularity-based query completion, MostPopularCompletion.

Suggests the past queries that extend the prefix with the highest log frequency, found by a top-k search in a scored trie.

Time
O(m + k L log(k L)) expected
Space
O(k L) extra
Where
L = the length of the longest logged query; k = the number of completions; m = the length of the prefix
Properties
deterministiciterative
Origin
Ziv Bar Yossef, Naama Kraus, 2011

Most popular completion is the method that answers a typed prefix with the kk past queries that start with it and were issued most often. Bar-Yossef and Kraus named it MostPopularCompletion in 2011 and showed that it is the maximum likelihood choice when the next query is assumed to follow the frequencies of the log. This page gives the fast top-kk search in a trie whose nodes store the largest count below them, the idea of the Completion Trie of Hsu and Ottaviano. The trie page covers the plain data structure, and query auto-completion covers the problem and the methods that use context, time or the user.

In plain words

A search engine remembers every query that people typed and how many times. When you have typed "bin", it looks at all the remembered queries that begin with "bin" and shows the few that were typed most often. The trick is to do this fast without looking at every query. The engine keeps the queries in a tree of letters, where each branch remembers the highest count of any query further down it. It then always follows the branch with the best remembered count, so it walks straight to the most popular queries and skips the branches that cannot win.

The problem

The log is a map from queries to counts: each query qq is a non-empty string and its count c(q)≥1c(q) \ge 1 is the number of times it was issued. For a prefix pp and an integer k≥0k \ge 0, return the queries qq with pp as a prefix, ordered by count descending, then by the query string ascending, and keep the first kk. The tie rule makes the answer unique. If P(q∣p)P(q \mid p) is estimated by c(q)c(q) divided by the total count of the queries that start with pp, this order is the order of the estimated probability, so the answer is the maximum likelihood top kk.

The algorithm

Build a trie over the log. Each node xx stores the count of the query that ends at it (0 if none), best(x)\mathrm{best}(x), the largest count in its subtree, and pre(x)\mathrm{pre}(x), its preorder number in a traversal that visits children in character order, so that preorder numbers sort like the strings. The children of each node are kept sorted by (−best,pre)(-\mathrm{best}, \mathrm{pre}). The search is best-first on a priority queue of nodes and finished queries, with the key (−best,pre,kind)(-\mathrm{best}, \mathrm{pre}, \text{kind}), where a finished query has kind 0 and a node kind 1:

  1. MOST-POPULAR(T, p, k) ▷ T: the scored trie of the log
  2. 1s ← root of T
  3. 2for each character a of p:
  4. 3if s has no child a then return the empty list
  5. 4s ← child a of s
  6. 5H ← heap with the node entry of s
  7. 6out ← empty list
  8. 7while H is not empty and |out| < k:
  9. 8e ← pop the entry with the smallest key from H
  10. 9if e is a finished query q then append (q, c(q)) to out; continue
  11. 10x ← the node of e
  12. 11if a query q ends at x then push q with key (−c(q), pre(x), 0)
  13. 12push the first child y of x with key (−best(y), pre(y), 1)
  14. 13if x ≠ s then push the next sibling z of x with key (−best(z), pre(z), 1)
  15. 14return out

Lines L12 and L13 follow the first-child and next-sibling links, so each node is pushed once, and a node is only expanded when its best count can still beat every entry in the heap. Building the trie takes one pass over the log to insert the queries and update best\mathrm{best} along each path, one traversal for the preorder numbers, and one sort of the children of each node.

Example

Take a log of seven queries:

query count
bing 80
binary search 50
bm25 40
binary search tree 30
bin packing 25
bit manipulation 20
binomial heap 15

For the prefix "bin" and k=3k = 3, lines L1 to L4 walk down to the node of "bin", whose best count is 80. Its children in the order of their best counts are "g" (80), "a" (50), " " (25) and "o" (15). The search pops "bin", then "bing" and its finished query, so "bing" (80) is the first answer. Next it expands the ten nodes of "binary search", one character at a time, because their best count 50 is larger than anything else in the heap, and returns "binary search" (50). The node of "binary search" still has the best count 30 below it, so the five nodes of " tree" come next and give "binary search tree" (30). The answer is bing, binary search, binary search tree. The search popped 17 nodes, the nodes on the three paths, and never entered "bin packing" or "binomial heap": their best counts 25 and 15 stayed in the heap behind the answers. For the prefix "bi" and k=5k = 5 the answer adds bin packing (25) and bit manipulation (20); "bm25" does not start with "bi".

Correctness

The file proofs/correctness.md gives the proof. Preorder numbers in character order sort the nodes like their strings, so the key order of finished queries is the tie order of the problem. The first-child and next-sibling links make a tree over the subtree of ss in which the keys of nodes grow from parent to successor, because a child cannot have a larger best count than its parent and a later sibling comes later in the sorted order. So when a query is popped, no query with a smaller key can still be hidden below an entry in the heap: that entry would have a smaller key than the popped one. The finished queries therefore leave the heap in the tie order, and the first kk of them are the answer.

Proof: The best-first trie search returns the top k completions in the tie orderfull

The log is a finite map from non-empty strings (queries) to positive integers (counts). The trie has one node for each prefix of a logged query, and the node of a string uu is written v(u)v(u). For a node xx, best(x)\mathrm{best}(x) is the largest count of a query in the subtree of xx, and pre(x)\mathrm{pre}(x) is the preorder number of xx in a traversal that visits the children in character order. The tie order on answers is count descending, then query ascending. The answer (q,c)(q, c) has the key κ(q)=(−c,pre(v(q)),0)\kappa(q) = (-c, \mathrm{pre}(v(q)), 0), and a node xx has the key κ(x)=(−best(x),pre(x),1)\kappa(x) = (-\mathrm{best}(x), \mathrm{pre}(x), 1). Keys are compared as tuples, and all keys are distinct.

Lemma 1 (preorder is string order). pre(v(u))<pre(v(w))\mathrm{pre}(v(u)) < \mathrm{pre}(v(w)) if and only if u<wu < w in string order, where a proper prefix is smaller than its extensions.

Proof. Let u≠wu \ne w. If uu is a proper prefix of ww, the traversal visits v(u)v(u) before every node of its subtree, so pre(v(u))<pre(v(w))\mathrm{pre}(v(u)) < \mathrm{pre}(v(w)), and u<wu < w. Else let zz be the longest common prefix, with next characters aa in uu and bb in ww, a≠ba \ne b. The traversal finishes the subtree of v(za)v(za) before it starts the subtree of v(zb)v(zb) exactly when a<ba < b, which holds exactly when u<wu < w. □\square

So the order of the answer keys is the tie order of the page.

Lemma 2 (search tree). In the search, the successors of a popped node xx are its first child in the order (−best,pre)(-\mathrm{best}, \mathrm{pre}), its next sibling in that order (not followed for the start node s=v(p)s = v(p)), and the answer that ends at xx. Every node and every answer of the subtree of ss is pushed exactly once, and a node successor has a larger key than xx.

Proof. The first-child and next-sibling links are the left-child, right-sibling form of the subtree of ss, so each node of the subtree is pushed exactly once, by its parent or by its previous sibling, and each answer once, by its node. For a child yy of xx, best(y)≤best(x)\mathrm{best}(y) \le \mathrm{best}(x) and pre(y)>pre(x)\mathrm{pre}(y) > \mathrm{pre}(x), so κ(y)>κ(x)\kappa(y) > \kappa(x). A next sibling comes later in the sorted order of the siblings, so its key is larger. □\square

The answer at xx can have a smaller key than xx, when its count is best(x)\mathrm{best}(x). Along a path of the search tree from ss to a node v(b)v(b), the keys increase, so every node zz on it has κ(z)≤κ(v(b))\kappa(z) \le \kappa(v(b)). (∗)(\ast)

Theorem 1 (output). For every prefix pp and every k≥0k \ge 0, the search returns the first min⁡(k,np)\min(k, n_p) answers that start with pp in the tie order, where npn_p is the number of logged queries that start with pp.

Proof. If v(p)v(p) does not exist, no query starts with pp and the search returns the empty list. Else, by Lemma 2, the answers that can appear are exactly the queries in the subtree of ss, which are the queries that start with pp. We show that they leave the heap in increasing key order. Suppose an answer aa is popped while an answer bb with κ(b)<κ(a)\kappa(b) < \kappa(a) has not been popped. On the search path from ss to v(b)v(b) and then to bb, the first element is pushed, so some element zz of the path is in the heap at that moment. If z=bz = b, then κ(z)<κ(a)\kappa(z) < \kappa(a). If zz is a node, then κ(z)≤κ(v(b))\kappa(z) \le \kappa(v(b)) by (∗)(\ast). With cbc_b the count of bb, best(v(b))≥cb\mathrm{best}(v(b)) \ge c_b. If the inequality is strict, κ(v(b))<κ(b)<κ(a)\kappa(v(b)) < \kappa(b) < \kappa(a). If it is an equality, κ(v(b))=(−cb,pre(v(b)),1)\kappa(v(b)) = (-c_b, \mathrm{pre}(v(b)), 1), and κ(a)>κ(b)=(−cb,pre(v(b)),0)\kappa(a) > \kappa(b) = (-c_b, \mathrm{pre}(v(b)), 0) with third entry 00 forces κ(a)>κ(v(b))\kappa(a) > \kappa(v(b)). In every case the heap holds a smaller key than κ(a)\kappa(a) when aa is popped, which is impossible. So the answers come out in increasing key order, which is the tie order by Lemma 1, and the loop stops after kk answers or when the heap is empty. □\square

Theorem 2 (work). Let LL be the length of the longest query. The search pops at most min⁡(k,np)⋅(L−∣p∣+1)\min(k, n_p) \cdot (L - |p| + 1) nodes.

Proof. If the search returns all npn_p answers, it pops at most every node of the subtree of ss. Each such node lies on the path from ss to the end of some query, because the trie has no node without a query below it, so there are at most np(L−∣p∣+1)n_p (L - |p| + 1) of them. Else the search stops at its kk-th answer tt, with count ctc_t. Let xx be a popped node, m=best(x)m = \mathrm{best}(x) and uu its string. When xx is popped, tt is not, so as in Theorem 1 some element zz of the path to tt is in the heap and κ(x)≤κ(z)\kappa(x) \le \kappa(z). By (∗)(\ast) and best(v(t))≥ct\mathrm{best}(v(t)) \ge c_t, this gives (−m,pre(x))≤(−ct,pre(v(t)))(-m, \mathrm{pre}(x)) \le (-c_t, \mathrm{pre}(v(t))) as pairs. Let bb be the answer of the subtree of xx with the smallest key; its count is mm. If m>ctm > c_t, then κ(b)<κ(t)\kappa(b) < \kappa(t), so bb is returned, and xx is on the path from ss to v(b)v(b). If m=ctm = c_t, then u≤tu \le t by Lemma 1. When uu is a prefix of tt, xx is on the path to v(t)v(t). Otherwise every extension of uu is smaller than tt, so κ(b)<κ(t)\kappa(b) < \kappa(t) and bb is returned. So every popped node lies on the path from ss to the node of a returned answer. There are at most min⁡(k,np)\min(k, n_p) answers and each path has at most L−∣p∣+1L - |p| + 1 nodes. □\square

Each node pop pushes at most three entries, so the heap never holds more than 3min⁡(k,np)(L−∣p∣+1)+13 \min(k, n_p)(L - |p| + 1) + 1 entries. The search costs O(∣p∣)O(|p|) expected time to walk down the prefix with hash table lookups, then O(kLlog⁡(kL))O(kL \log(kL)) time for the heap. The test file checks Theorem 1 against a sort of the whole log for every prefix and every kk on random logs, and checks the bound of Theorem 2.

Complexity

Every node that the search pops lies on the path from ss to one of the returned queries. A node with a best count above the kk-th answer has a winner below it, and a node with the same best count but a smaller string either is a prefix of the kk-th answer or holds only smaller strings, which are returned. So at most min⁡(k,np)(L−m+1)\min(k, n_p)(L - m + 1) nodes are popped, where npn_p is the number of queries with the prefix, and each pop pushes at most three entries. With hash tables for the children, the walk down the prefix costs O(m)O(m) expected time and the search O(kLlog⁡(kL))O(kL \log(kL)), with O(kL)O(kL) extra space for the heap. Building the trie costs O(Tlog⁡σ)O(T \log \sigma) time for a log with TT characters in total and at most σ\sigma children per node, and the trie has at most T+1T + 1 nodes. The baseline that filters and sorts the whole log costs O(nL+nlog⁡n)O(nL + n \log n) time for each prefix, for nn logged queries.

Properties

  • Exact. The answer is the exact top kk of the log under the tie rule, not an approximation.
  • Output-sensitive. The work depends on kk and on the length of the answers, not on the number of queries with the prefix.
  • Static scores. The counts are fixed when the trie is built. A change of one count changes best\mathrm{best} on the whole path to the root and the order of siblings along it.
  • Deterministic. Equal logs and prefixes give equal answers.

Variants and improvements

  • Compact tries. Hsu and Ottaviano store the Completion Trie with path compression, as in a radix tree, and compress the scores; they report about a microsecond per completion with space competitive with gzip of the log. Their Score-Decomposed Trie and RMQ Trie are other layouts with the same output.
  • Sorted array and range minimum queries. Sort the queries; the queries with a given prefix form one range, found by binary search. The top kk of a range come from a range minimum query structure over the negated counts: take the minimum, split the range around it, and keep the parts in a heap. Gog, Pibiri and Venturini build their system on this idea.
  • Precomputed lists. Store the top kk answers at every node, or at every node near the root. A lookup is then a walk down the prefix, at the cost of kk entries for each stored node.
  • Time-sensitive counts. Replace raw counts with counts that decay with age, or with counts predicted for the next hours, so that new and seasonal queries rise. Cai and de Rijke survey these methods.
  • Context and personal history. Bar-Yossef and Kraus rerank the popular candidates by their similarity to the previous queries of the session (NearestCompletion), and combine the two scores (HybridCompletion).
  • Fuzzy prefixes. Allow a few edits in the prefix, so that a typo in the first letters does not hide the right completions. See noisy channel spelling correction for a model of the errors.

When to use it

Use most popular completion as the first method for any query box with a large log, and as the baseline against which context-aware or learned methods are measured. It needs only counts, it is exact and fast, and for short prefixes the most frequent queries are usually good guesses. It is weak for rare prefixes with few logged queries, for new events that the log has not seen often yet, and when the same prefix means different things to different users.

Pitfalls

  • Ties. Many queries share a count, especially rare ones. Without a tie rule the shown list can change from one build to the next.
  • Unsafe and private queries. A raw log contains queries that should not be suggested, such as offensive text or personal data. Filter the log before building the trie.
  • Stale counts. Counts over a long period favour old queries. Use a time window or decay.
  • Updates. Raising one count can reorder siblings on the whole path to the root. Batch the updates and rebuild, or use a structure built for updates.
  • Normalization. Decide on case, spaces and Unicode forms before counting, or the counts of one query split over several strings.
  • Very short prefixes. For one letter the answers are the global top queries, which are the same for everyone and often not useful. Many systems show nothing until a few letters are typed.

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.

most_popular_completion.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/most-popular-completion/. The authors are listed in prov/PB06E3.jsonl.
"""Most popular completion with a scored trie.

The log maps each past query to its count. For a prefix p, the answer is
the k logged queries that start with p, in the order count descending,
then query string ascending (Python string order). This is the tie rule
of the page.

Each trie node stores the largest count in its subtree (best) and its
preorder number (pre) in a traversal that visits the children in
character order, so pre orders the nodes as their strings sort. The
children of each node are also kept in the order (-best, pre), as in the
Completion Trie of Hsu and Ottaviano (2013). The search is best-first on
a heap with the key (-best, pre, kind): popping a node pushes its first
child and its next sibling, and the query that ends at it.
"""

import heapq

_QUERY = 0  # a finished query sorts before the node with the same string
_NODE = 1


class _Node:
    __slots__ = ("children", "order", "count", "query", "best", "pre", "next")

    def __init__(self):
        self.children = {}  # character -> child node
        self.order = []  # children sorted by (-best, pre)
        self.count = 0  # count of the query that ends here, 0 if none
        self.query = None  # the query that ends here
        self.best = 0  # largest count in the subtree
        self.pre = 0  # preorder number in character order
        self.next = None  # next sibling in the order (-best, pre)


class CompletionTrie:
    """A trie over a query log, with the top-k search of the page."""

    def __init__(self, log: dict[str, int]):
        self.root = _Node()
        self.pops = 0  # node pops of the last call of top_k
        for query, count in log.items():
            if not isinstance(query, str) or query == "":
                raise ValueError("queries must be non-empty strings")
            if count <= 0:
                raise ValueError("counts must be positive")
            node = self.root
            node.best = max(node.best, count)
            for ch in query:
                node = node.children.setdefault(ch, _Node())
                node.best = max(node.best, count)
            node.count = count
            node.query = query
        self._number()

    def _number(self) -> None:
        """Give preorder numbers in character order, then link the siblings."""
        counter = 0
        stack = [self.root]
        nodes = []
        while stack:
            node = stack.pop()
            node.pre = counter
            counter += 1
            nodes.append(node)
            for ch in sorted(node.children, reverse=True):
                stack.append(node.children[ch])
        for node in nodes:
            node.order = sorted(node.children.values(), key=lambda c: (-c.best, c.pre))
            for a, b in zip(node.order, node.order[1:]):
                a.next = b

    def top_k(self, prefix: str, k: int) -> list[tuple[str, int]]:
        """The k most frequent logged queries that start with prefix."""
        self.pops = 0
        node = self.root  # @line L1
        for ch in prefix:  # @line L2
            child = node.children.get(ch)
            if child is None:  # @line L3
                return []
            node = child  # @line L4
        start = node
        heap = [(-start.best, start.pre, _NODE, start)]  # @line L5
        out: list[tuple[str, int]] = []  # @line L6
        while heap and len(out) < k:  # @line L7
            _, _, kind, x = heapq.heappop(heap)  # @line L8
            if kind == _QUERY:  # @line L9
                out.append((x.query, x.count))
                continue
            self.pops += 1  # @line L10
            if x.count > 0:  # @line L11
                heapq.heappush(heap, (-x.count, x.pre, _QUERY, x))
            if x.order:  # @line L12
                first = x.order[0]
                heapq.heappush(heap, (-first.best, first.pre, _NODE, first))
            if x is not start and x.next is not None:  # @line L13
                y = x.next
                heapq.heappush(heap, (-y.best, y.pre, _NODE, y))
        return out  # @line L14


def scan_top_k(log: dict[str, int], prefix: str, k: int) -> list[tuple[str, int]]:
    """The baseline without an index: filter the whole log and sort it."""
    hits = [(q, c) for q, c in log.items() if q.startswith(prefix)]
    hits.sort(key=lambda qc: (-qc[1], qc[0]))
    return hits[: max(k, 0)]
test_most_popular_completion.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/most-popular-completion/. The authors are listed in prov/PB06E3.jsonl.

import random

import pytest

from most_popular_completion import CompletionTrie, scan_top_k

# The log of the example on the page.
LOG = {
    "bing": 80,
    "binary search": 50,
    "bm25": 40,
    "binary search tree": 30,
    "bin packing": 25,
    "bit manipulation": 20,
    "binomial heap": 15,
}


def brute(log, prefix, k):
    """Sort the whole log by the tie rule: count descending, then query ascending."""
    ranked = sorted(log.items(), key=lambda qc: (-qc[1], qc[0]))
    return [qc for qc in ranked if qc[0].startswith(prefix)][:k]


def random_log(rng, size, alphabet, max_len, max_count):
    log = {}
    while len(log) < size:
        n = rng.randint(1, max_len)
        q = "".join(rng.choice(alphabet) for _ in range(n))
        log[q] = rng.randint(1, max_count)
    return log


def test_example_of_the_page():
    t = CompletionTrie(LOG)
    assert t.top_k("bin", 3) == [("bing", 80), ("binary search", 50), ("binary search tree", 30)]
    assert t.top_k("bi", 5) == [
        ("bing", 80),
        ("binary search", 50),
        ("binary search tree", 30),
        ("bin packing", 25),
        ("bit manipulation", 20),
    ]
    assert t.top_k("b", 2) == [("bing", 80), ("binary search", 50)]
    assert t.top_k("binary", 10) == [("binary search", 50), ("binary search tree", 30)]
    assert t.top_k("c", 3) == []
    assert t.top_k("bin", 0) == []


def test_tie_rule_uses_the_query_string():
    log = {"ab": 5, "aa": 5, "a": 5, "abc": 5, "b": 9}
    t = CompletionTrie(log)
    assert t.top_k("", 5) == [("b", 9), ("a", 5), ("aa", 5), ("ab", 5), ("abc", 5)]
    assert t.top_k("a", 2) == [("a", 5), ("aa", 5)]


@pytest.mark.parametrize("seed", range(40))
def test_every_prefix_matches_brute_force(seed):
    rng = random.Random(seed)
    alphabet = "abc" if seed % 2 == 0 else "ab c"
    log = random_log(rng, rng.randint(1, 40), alphabet, 6, rng.choice([3, 20, 1000]))
    t = CompletionTrie(log)
    longest = max(len(q) for q in log)
    prefixes = {""} | {q[:i] for q in log for i in range(len(q) + 1)}
    prefixes |= {"".join(rng.choice(alphabet) for _ in range(rng.randint(1, 4))) for _ in range(20)}
    for p in sorted(prefixes):
        n_p = sum(1 for q in log if q.startswith(p))
        for k in range(0, len(log) + 2):
            got = t.top_k(p, k)
            assert got == brute(log, p, k) == scan_top_k(log, p, k)
            # Every popped node lies on the path from the prefix node to an answer.
            assert t.pops <= min(k, n_p) * (longest - len(p) + 1)


def test_rejects_bad_logs():
    with pytest.raises(ValueError):
        CompletionTrie({"a": 0})
    with pytest.raises(ValueError):
        CompletionTrie({"": 3})

History

Query suggestion from logs was part of web search engines before the research papers named the method. Bar-Yossef and Kraus defined MostPopularCompletion in 2011 as the maximum likelihood estimator from the log and used it as the baseline for context-sensitive completion. Hsu and Ottaviano studied the data structures for the top-kk search in 2013 and gave three compact tries. Gog, Pibiri and Venturini returned to the efficiency question in 2020 with an index built on range minimum queries. Cai and de Rijke surveyed the field in 2016.

References

  1. Ziv Bar-Yossef and Naama Kraus, Context-sensitive query auto-completion, Proceedings of the 20th International Conference on World Wide Web (WWW 2011), 107-116, the definition of MostPopularCompletion as the maximum likelihood estimate of the next query from the frequencies in the log, used as the baseline of the context-sensitive methods NearestCompletion and HybridCompletion
  2. Bo-June (Paul) Hsu and Giuseppe Ottaviano, Space-efficient data structures for top-k completion, Proceedings of the 22nd International Conference on World Wide Web (WWW 2013), 583-594, the Completion Trie, with the children of each node sorted by score and a best-first search on a priority queue, and the RMQ Trie and the Score-Decomposed Trie; the measured times of about a microsecond per completion
  3. Fei Cai and Maarten de Rijke, A survey of query auto completion in information retrieval, Foundations and Trends in Information Retrieval 10(4), 273-363, 2016, the chapters on popularity-based methods (heuristic and learned), on time-sensitive and user-sensitive methods, and on efficiency
  4. Simon Gog, Giulio Ermanno Pibiri and Rossano Venturini, Efficient and effective query auto-completion, Proceedings of the 43rd International ACM SIGIR Conference (SIGIR 2020), arXiv:2005.06213, the top-k completions of a prefix as the k smallest values in a lexicographic range of the sorted log, found by range minimum 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • 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
  • a scene preset for the example