Abstract 1 Introduction 2 Problem Presentation 3 Prerequisites 4 Blocking Technique 5 Overview and Strategy 6 Solving the Subtasks 7 Faster Path 𝜶-Minority Queries on Trees References

Faster Linear-Space Data Structures for Path Frequency Queries

Ovidiu Rața ORCID University of Copenhagen, Denmark
Abstract

We present linear-space data structures for several frequency queries on trees, namely: path mode, path least frequent element, and path α-minority queries. We present the first linear-space data structures, requiring O(nnw) preprocessing time, that can answer path mode and path least frequent element queries in O(n/w) time. This improves upon the best previously known bound of O(loglognn/w) achieved by Durocher et al. [10] in 2016.

For the path α-minority problem, where α is specified at query time, we reduce the query time of the linear-space data structure of Durocher et al. [10] from O(α1loglogn) down to O(α1) by employing a simple randomized algorithm with a success probability 1/2.

We also present the first linear-space data structure supporting “Path Maximum g-value Color” queries in O(n/w) time, requiring O(nnw) preprocessing time. This general framework encapsulates both path mode and path least frequent element queries. For our data structures, we consider the word-RAM model with wΩ(logn), where w is the word size in bits.

Keywords and phrases:
Data structure, Range query, Mode, Minority, Least frequent element, Trees, Linear-space, Path query
Copyright and License:
[Uncaptioned image] © Ovidiu Rața; licensed under Creative Commons License CC-BY 4.0
2012 ACM Subject Classification:
Theory of computation Sorting and searching
Related Version:
Full Version: https://arxiv.org/abs/2604.18667 [14]
Acknowledgements:
I wish to thank Professor Mikkel Thorup for his valuable support as my Master’s Thesis supervisor. I also wish to thank the anonymous reviewers of SWAT 2026 for their meaningful feedback, which helped improve the paper.
Funding:
Supported by VILLUM Foundation grant 54451, Basic Algorithms Research Copenhagen (BARC).
Editor:
Pierre Fraigniaud

1 Introduction

According to Chan et al. [6], given a multiset S, the frequency of an element x in S, denoted by freqS(x), is the number of occurrences of the element x in S. A mode of S is an element aS such that for all xS , freqS(x)freqS(a). Given an array A of n integers, a range mode of A[i:j] is a mode of the multiset determined by the range A[i:j]. Alternatively, one least frequent element in a multiset A is an element of minimum multiplicity in A.

Generalizing the range mode query problem to trees, we study the problem of building a data structure that, given two nodes (i,j), can efficiently find the mode of the multiset of nodes of the path P(i,j). An alternative to the path mode query is the path least frequent element query, which asks to report any single element on the path P(i,j) of minimal multiplicity.

Historically, there has always been a gap between the query times for the array and tree versions of the mode and least frequent element problems. Chan et al. [6] developed the fastest known linear-space data structure with O(n/w) query time for the array mode query problem, while the time for tree path queries remained O(lognn). Later, in 2016, Durocher et al. [10] reduced the time on trees down to O(loglognn/w), for both mode and least frequent element queries. In this paper, we bridge this gap by reducing the time for both path mode queries and least frequent element queries on trees down to O(n/w), in the context of linear-space data structures.

We also consider a new, more general problem, which we call the Range Maximum g-value Color query. By abstracting specific frequency conditions into a generic function g, we provide a unified algorithmic framework that simultaneously solves both the mode and least frequent element problems, while also capturing more complex frequency-based metrics. An array A of n positive integers (the “array of colors”) and a function g are given. We require g to satisfy several properties, which are also satisfied by the range mode function. A detailed formal definition of these properties is provided in Section 2.

The Range Maximum g-value Color problem is to preprocess A and the function g to efficiently answer queries of the following form:

Given two indices i,j of A, determine: argmaxcA[ij]{g(i,j,c)}

In other words, the query asks to report any single color c corresponding to the maximum value of g(i,j,c).

We study the generalization of this problem to trees, which we call Path Maximum g-value Color, and prove that there exists a linear-space data structure supporting these queries in O(n/w) time, requiring O(nnw) preprocessing time. Because this problem acts as a generalization, it directly reduces the O(loglognn/w) worst-case query time required by the previous linear-space data structures for path mode and path least frequent element queries [10], down to O(n/w).

We conclude our work by presenting an improvement over the path α-minority problem, studied by Durocher et al. [10]. The path α-minority query for a tree path (u,v) asks to report any single color that occurs at most an α fraction of the time on the path between nodes u and v. We prove that by applying a simple randomized algorithm with success probability 1/2, their linear-space data structure can support α-minority queries in O(α1) time (where α is specified at query time), improving on the previous O(α1loglogn) query time.

We assume the Word RAM model of computation using words of w=Ω(logn) bits, where n=|A|.

1.1 Related Work and Contribution

Krizanc et al. [13] presented O(n)-space data structures that support range mode queries in O(nloglogn) time on arrays and O(nlogn) time on trees. Chan et al. [6] achieved o(n) query time with an O(n)-space data structure that supports queries in O(n/w)O(n/logn) time on arrays. Durocher et al. [10] present an O(n) space data structure supporting path mode queries on trees in O(loglognn/w) time. Durocher et al. [10] ask whether the loglogn gap between the path mode query time on trees and the range mode query time on arrays can be closed. In this paper, we present the first O(n) space data structure that supports path mode queries in O(n/w)o(loglognn/w) query time, thus eliminating the gap between path mode and range mode query times.

In the context of the least frequent element problem, Chan et al. [7] presented an O(n)-space data structure that supports range least frequent element queries on arrays in O(n) time. Durocher et al. [10] improve the range least frequent element query time down to O(n/w), and designed the first path least frequent element query data structure for trees, with an O(loglognn/w) query time. In our paper, we present the first linear-space data structure that supports path least frequent element queries on trees in O(n/w) time, thus also closing the loglogn gap between the array and tree query times for this problem. A history of previous best query times, achieved by linear-space data structures for mode queries and least frequent element queries, is presented in Tables 1, 2.

Table 1: History of Mode Queries (linear-space).
Authors Array Query Time Tree Query Time Source
Krizanc et al. O(nloglogn) O(nlogn) [13]
Chan et al. O(n/w) [6]
Durocher et al. O(loglognn/w) [10]
This Paper 𝐎(𝐧/𝐰)
Table 2: History of Least Frequent Element Queries (linear-space).
Authors Array Query Time Tree Query Time Source
Chan et al. O(n) [7]
Durocher et al. O(n/w) O(loglognn/w) [10]
This Paper 𝐎(𝐧/𝐰)

In their work, Durocher et al. [10] present a linear-space data structure that can answer path α-minority queries on trees in O(α1loglogn) time, with α specified at query time. The path α-minority query for a tree path (u,v) asks to report any color that occurs at most an α fraction of the tree path between nodes u and v. We prove that by applying a simple randomized algorithm with success probability 1/2, their linear-space data structure can support α-minority queries in O(α1) time, improving on the previous O(α1loglogn) query time. A history of query times achieved by linear-space data structures for α-minority is given in Table 3.

Table 3: History of α-Minority Queries (linear-space).
Authors Array Query Time Tree Query Time Source
Chan et al. O(1/α) [7]
Durocher et al. O(α1loglogn) [10]
This Paper 𝐎(𝟏/α) (Randomized)

2 Problem Presentation

We begin with a detailed formalization of the main problem studied in this paper, namely, the Path Maximum g-value Color problem. We formulated this problem to generalize the path mode query problem as broadly as possible. We also note that we present the first efficient linear-space data structure for the range version of the maximum g-value color problem, as this general problem has not been studied previously.

Our study of this problem and the methods used to solve it were inspired by the domain of retrieval/counting problems and array range query problems. A description of retrieval/counting problems is given by Chazelle [8], and some interesting instances of array range query problems can be found in Skala et al. [15]. For clarity, we first present the problem in the context of arrays, and subsequently generalize it to trees.

2.1 The Range Maximum 𝒈-value Color Problem

An instance of our problem consists of an array of integers A (referred to as the “array of colors”) and an integer function g. Let n=|A|. We assume that 1A[i]n. If A does not fulfill this requirement, A can be transformed in O(nlogn) time to an array A with values compressed to the interval {1,,n}.

The starting point of our study was the range mode function. We developed our data structure using only a subset of the properties of the range and path mode functions. We require g to satisfy the following constraints, all of which are shared by the range mode function:

  1. 1.

    Domain: The function g(i,j,c) takes three integer arguments, where 1ijn are indices of A, and c is a color present in the subarray A[ij].

  2. 2.

    Output: g produces an integer output that fits into a single machine word.

  3. 3.

    Range Contraction: For any valid input (i,j,c),

    g(i,j,c)=g(i,j,c)

    where i and j are the minimum and maximum indices, respectively, such that iijj and A[i]=A[j]=c. In other words, the value of g depends only on the range spanned by the occurrences of c within the query interval.

  4. 4.

    Oracle Complexity: We assume g can be computed efficiently given a contracted range. Specifically, computing g(i,j,c) such that A[i]=A[j]=c takes O(1) time. This computation may use an additional O(n)-space static data structure.

The Range Maximum g-value Color problem is to preprocess A and the function g to efficiently answer queries of the following form:

Given two indices i,j of A, determine: argmaxcA[ij]{g(i,j,c)}

In other words, determine any single color c corresponding to the maximum value of g(i,j,c).

2.2 Generalization to trees

This problem generalizes naturally to trees. Instead of an array, we are given a rooted, node-colored tree 𝒯 and a function g defined on tree paths. An input to g consists of a triple (u,v,c), where u,v are nodes in 𝒯 and c is a color occurring on the simple path P(u,v). From now on, we will consider 𝒯 to be rooted at node 1.

The properties of g remain analogous. Crucially, the Range Contraction property (Property 3) translates as follows:

g(u,v,c)=g(u,v,c)

where u is the node on P(u,v) closest to u such that 𝒯[u]=c, and v is the node on P(u,v) closest to v such that 𝒯[v]=c, where 𝒯[u] denotes the color of node u in the tree 𝒯.

We refer to this generalized problem as the Path Maximum g-value Color problem. This is the main problem we focus on in our work. In the following sections, we present a linear-space data structure supporting path maximum g-value color queries in O(n/w) time, requiring O(nnw) preprocessing time.

2.3 Applications of the path maximum g-value color problem

To motivate why this abstract definition is interesting in its own right, we introduce the Range Maximum Sum Color problem. Given a color array A and a cost array V, we wish to find the color in a range A[ij] that maximizes the sum of its associated costs. Formally:

argmaxcA[ij]{k[i,j]:A[k]=cV[k]}

This is a specific instance of the maximum g-value color problem, as the summation function satisfies all properties of g (specifically, the sum of costs for color c in range [i,j] is identical to the sum in the contracted range [i,j]).

This problem, again, naturally generalizes to trees; thus, we obtain the Path Maximum Sum Color problem. By using the virtual tree data structure, and Lemma 2 presented in Section 3, we can easily verify that:

g(uc,vc,c)={g(uc,rc,c)+g(vc,rc,c)2g(lca,rc,c)lcaP(uc,vc)g(uc,rc,c)+g(vc,rc,c)2g(lca,rc,c)+V[lca]lcaP(uc,vc) (1)

where lca is the lowest common colored ancestor of uc and vc (which requires 𝒯 to be rooted), uc,vc are both c-colored nodes, and rc is the root of the virtual tree of color c. We can verify that g(uc,vc,c) can be computed in O(1) time using relation 1 if we store for each uc the values g(uc,rc,c) in a table of size O(n).

Both on arrays and on trees, the Maximum Sum Color problem acts as a generalization for both the Mode problem (where V[k]=1 for all k) and the Least Frequent Element problem (where V[k]=1 for all k, allowing us to maximize the negated sum).

2.3.1 Practical Example: Financial Time Series

As an additional motivation towards the independent study of the Range Maximum g-value Color problem, consider a log of chronologically ordered stock records: “Stock c changed by value v”. Storing stock IDs in A and changes in V, the Maximum Sum Color problem answers: “Which stock had the highest net increase/decrease between time i and j?”

Furthermore, our general g-value framework allows for more complex queries, such as identifying the stock with the maximum mean fluctuation per record within a time period, provided the mean is calculated over the stock’s records. This demonstrates that the g-value framework extends beyond standard frequency queries to elegantly handle cumulative weights and penalties.

2.4 Hierarchy and Contribution

We conclude this section by outlining the difficulty hierarchy. We focus on solving the most general variant: the Path Maximum g-value Color problem on trees. We present a linear-space data structure for this problem with a query time of O(n/w). Remarkably, this matches the query time of the fastest known data structure for the range mode query problem (Chan et al. [6]), which corresponds to the simplest case in our hierarchy.

Figure 1: The hierarchy of problems ordered by increasing difficulty and generality. The max. g-value color problem generalizes the max. sum color problem, which covers both the mode and least frequent element problems.

3 Prerequisites

We mention that we consider the colored tree 𝒯 given as input to be rooted at node 1. Prior to presenting our solution, we introduce several prerequisite results and definitions. We rely on the following standard results for tree data structures:

Lemma 1 (Bender and Farach-Colton [3]; Berkman et al. [5]; Dietz [9]).

There exists a linear-space data structure supporting level ancestor queries on trees in O(1) time, requiring O(n) preprocessing time.

Lemma 2 (Bender and Farach-Colton [2]; Berkman and Vishkin [4]).

There exists a linear-space data structure supporting lowest common ancestor (LCA) queries on trees in O(1) time, requiring O(n) preprocessing time.

3.1 Virtual Trees

We define virtual trees, which are essential for our data structure.

Definition 3.

Given a colored tree 𝒯 and a color c, the virtual tree of color 𝐜, denoted 𝒱c, is a rooted tree defined over the set of nodes {v𝒯color(v)=c}.

The structure of 𝒱c is defined by the following parent relationship: for any node v𝒱c, the parent of v in 𝒱c is the nearest proper ancestor of v in 𝒯 that also has color c.

To ensure 𝒱c is a single connected tree (rather than a forest), we introduce a virtual root node rc for each color c. If a node v of color c has no ancestors of color c in 𝒯, we set its parent in 𝒱c to be rc.

It is possible to construct all virtual trees 𝒱c for all colors c in O(n) total time using a single depth-first traversal of 𝒯. Since the node sets for each color form a partition of the colored nodes in 𝒯, the total space required is linear, O(n). We defer the algorithm for computing all the virtual trees 𝒱c to the full version of this paper, available as a preprint on arXiv [14].

By applying standard LCA and Level Ancestor structures (Lemmas 1 and 2) to these virtual trees, we obtain the following corollary:

Corollary 4.

There exists a linear-space data structure, constructed in O(n) time, that answers the following queries in O(1) time:

  1. 1.

    Given two nodes u,v𝒯 of the same color c, determine the lowest common ancestor of u and v with respect to color c (i.e., the LCA of u and v in 𝒱c).

  2. 2.

    Given a node u of color c and an integer k, determine the k-th ancestor of u of color c (i.e., the k-th ancestor of u in 𝒱c).

Proof.

For each distinct color c present in 𝒯, we explicitly construct the virtual tree 𝒱c. Over each 𝒱c, we build instances of the data structures described in Lemmas 1 and 2.

Let nc=|V(𝒱c)|. The construction and preprocessing for a specific color c takes O(nc) time and space. Summing over all colors, the total preprocessing time is cO(nc)=O(n), and the total space is similarly cO(nc)=O(n). The queries are answered by querying the specific structure for 𝒱c in O(1) time.

4 Blocking Technique

Krizanc et al. [13], Chan et al. [6, 7], and Durocher et al. [10] successfully employed blocking techniques to solve non-trivial frequency queries on arrays and trees. We adapt their framework to develop a multi-level blocking strategy, allowing us to achieve the desired query time for path maximum g-value color queries on trees.

Lemma 5 (Durocher et al. [10]).

Let 𝒯 be a tree with n nodes, and let t<n be an integer parameter (the blocking factor). There exists a subset of marked nodes MtV(𝒯) and an associated rooted tree 𝒯t with vertex set Mt, satisfying the following properties:

  1. 1.

    Size: |Mt|=O(n/t);

  2. 2.

    LCA Closure: Mt is closed under the lowest common ancestor operation (i.e., for any u,vMt, the lowest common ancestor of u and v in 𝒯 is also in Mt);

  3. 3.

    Gap Size: Any simple path in 𝒯 consisting entirely of unmarked nodes has length at most t.

Two nodes u,vMt are adjacent in 𝒯t if and only if the simple path between them in 𝒯 contains no other nodes from Mt. The set Mt and the tree 𝒯t can be constructed in O(nlogn) time.

Lemma 6 (Durocher et al. [10]).

Given a tree 𝒯 with n nodes, an integer t<n, and a set of marked nodes Mt (obtained according to Lemma 5), there exists a partition of the vertex set V(𝒯), denoted by t={B1,,Bk}, satisfying the following properties:

  1. 1.

    Block Count: The number of blocks is k=O(n/t);

  2. 2.

    Block Size: For each block Bt, the number of nodes is |B|=O(t);

  3. 3.

    Connectivity: For each block Bt, the subgraph of 𝒯 induced by the nodes in B is connected.

The partition t can be computed in O(nlogn) time.

We defer the full details of the proofs of Lemmas 5 and 6 to the full version of this paper [14]. Further, for our approach, we require a multilevel partition of the nodes of 𝒯. From Lemma 6, we derive the following corollary, which formalizes the construction of a hierarchical partition.

Corollary 7.

Given a colored tree 𝒯, two blocking factors t1<t2, and the set of marked nodes Mt1 with its associated tree 𝒯t1 (obtained according to Lemma 5), there exists a subset Mt2Mt1 and a partition t2/t1 of Mt1, and a tree 𝒯t2.

These can be computed in O(|Mt1|log|Mt1|) time and satisfy the following properties:

  1. 1.

    Consistency: The set Mt2 is a valid set of marked nodes for 𝒯 with blocking factor t2 (satisfying all properties of Lemma 5).

  2. 2.

    Relative Gap: Any simple path in the compressed tree 𝒯t1 consisting entirely of nodes from Mt1Mt2 has length O(t2/t1).

  3. 3.

    Partition Structure: The partition t2/t1 divides the nodes of Mt1 into O(|Mt1|t1t2) blocks, each of size O(t2/t1), such that the subgraph of 𝒯t1 induced by each block is connected.

Proof.

We apply the construction procedures from Lemma 5 and Lemma 6 directly to the compressed tree 𝒯t1, treating it as the input tree with a blocking factor of t=t2/t1. Since |V(𝒯t1)|=|Mt1|, the construction requires O(|Mt1|log|Mt1|) time. The resulting marked nodes Mt2 and partition t2/t1 satisfy the size and connectivity properties with respect to 𝒯t1 by definition. Furthermore, since Mt1 preserves the LCA closure property of 𝒯, and Mt2 is constructed to preserve LCA closure on 𝒯t1, Mt2 maintains the necessary topological properties for 𝒯.

Crucially, the partition t2/t1 of Mt1 implicitly defines a coarser partition t2 of the original vertex set V(𝒯). A high-level block Bt2 consists of a set of connected low-level blocks from t1. To enumerate the nodes of a high-level block Bt2, we identify the corresponding block of marked nodes Bt2/t1 (where BMt1) and iterate through the low-level block Bu′′t1 associated with each uB.

Corollary 8.

Given a colored tree 𝒯, two blocking factors t1<t2, and the respective partitions into blocks computed according to Lemma 6 and Corollary 7, we can compute in O(|Mt1|) time, for each block B2t2/t1, a tree 𝒯t2/t1[B2], which is the subtree of Tt1 induced by the nodes in B2 (which are also present in Mt1).

Proof.

By Property 3 of Corollary 7, the subgraph of 𝒯t1 induced by any block Bt2/t1 is connected. Since 𝒯t1 is a tree, any connected subgraph is also a tree. To construct these explicit tree representations, we iterate through the edges of 𝒯t1. For each edge (u,v)E(𝒯t1), if both u and v belong to the same block Bt2/t1, we add the edge to 𝒯t2/t1[B]. This traversal visits every edge exactly once, resulting in a total runtime of O(|V(𝒯t1)|)=O(|Mt1|). We refer to 𝒯t2/t1[B2] as the block tree of B2. We depict an example of a 2-level block partition in Figure 2.

Figure 2: A 2-level partition of a tree. The representatives of a block are depicted with black dots. t1-blocks are depicted by circles, and t2-blocks by dashed splinoids. An example representative node u is chosen, and its respective blocks B1(u) and B2(u) are depicted.

We define the notions of home blocks for nodes and node representatives for blocks.

Definition 9 (Home Blocks and Representatives).

For any node uV(𝒯) and level k, let Bk(u) denote the unique block in the partition tk that contains u. We assume each block Btk is associated with a unique representative node in Mtk.

This definition allows us to examine a nested structure around a node u. The node u resides in a local block B1(u), which is nested within B2(u), which is further nested within B3(u) and so on.

4.1 Parameter Selection

For our specific data structure, we employ a 3-level partition of 𝒯. We assume the first blocking factor t1 is provided as a parameter. We then define the higher-level factors as follows:

t2=t1loglogn,t3=t2logn

During the preprocessing phase, we compute the associated structures Mti, 𝒯ti, and ti for 1i3. Specifically, we construct the full block partitions ti using the hierarchical method described in Corollary 7. Based on the established results, this entire preprocessing step requires O(nlogn) time.

5 Overview and Strategy

Having established the prerequisites, we now provide a high-level overview of our query answering strategy. Our approach refines the blocking technique of Durocher et al. [10]. In their solution, the query algorithm identifies a set of O(n/w) candidate nodes. For every distinct color appearing in this set of nodes, they perform a frequency verification step taking O(loglogn) time.

To improve upon this, we introduce a hierarchical candidate selection process. Instead of a single set, we identify two distinct sets of candidate nodes, denoted S1 and S2. These sets act as proxies for the colors we need to verify:

  • Primary Candidate Nodes (S𝟏): A small set of nodes (|S1|=O(t1)). For every color c appearing in S1, we perform a standard verification taking O(loglogn) time.

  • Secondary Candidate Nodes (S𝟐): A larger set of nodes (|S2|=O(t2)). For every color c appearing in S2, we store a triple (c,l,r), where l and r are the first occurrences of c, when traversing the path in the direction ij and ji, respectively. We need only O(1) time to compute g(c,l,r) for one such color.

This split allows us to process a larger total number of candidate nodes (and thus potential colors) without degrading the overall query complexity.

5.1 Decomposition into Disjoint Subtasks

To efficiently identify these candidate nodes, we decompose the query based on the hierarchy of blocks defined in Section 4. We decompose the problem into disjoint subtasks by partitioning the set of distinct colors present on the query path. Each subtask identifies a unique subset of colors based on their presence or absence in the hierarchical blocks surrounding i and j.

Let Cpath=C(P(i,j)) denote the set of all distinct colors present on the query path. For any block B, let C(B) denote the set of distinct colors present in that block.

We define the complement of a block’s color set with respect to the entire tree. Let 𝒰 be the universe of all distinct colors in the tree 𝒯. We define:

C(B)¯=𝒰C(B)

This represents the set of all colors in the tree that are not present in block B.

The set of path colors Cpath is partitioned into the following disjoint subsets C1,,C10 using intersection operations on these color sets:

  • 1. The Global Colors: C1=CpathC(B3(i))¯C(B3(j))¯.

    Colors on the path that are not present in the Level 3 blocks of either endpoint.

  • 2. The Level 3 Ascent: C2=CpathC(B3(i))C(B2(i))¯C(B3(j))¯.

    Colors on the path that are in i’s Level 3 block, but not in i’s Level 2 block or j’s Level 3 block.

  • 3. The Level 2 Ascent: C3=CpathC(B2(i))C(B1(i))¯C(B3(j))¯.

    Colors on the path that are in i’s Level 2 block, but not in i’s Level 1 block or j’s Level 3 block.

  • 4. The Level 3 Descent: C4=CpathC(B3(j))C(B2(j))¯C(B3(i))¯.

    Symmetric to C2.

  • 5. Level 3 Intersection: C5=CpathC(B3(i))C(B3(j))C(B2(i))¯C(B2(j))¯.

    Colors on the path present in both Level 3 blocks, but in neither Level 2 block.

  • 6. Mixed Intersection: C6=CpathC(B2(i))C(B3(j))C(B1(i))¯C(B2(j))¯.

    Colors on the path present in i’s Level 2 block and j’s Level 3 block, excluding inner blocks.

  • 7. The Level 2 Descent: C7=CpathC(B2(j))C(B1(j))¯C(B3(i))¯.

    Symmetric to C3.

  • 8. Mixed Intersection: C8=CpathC(B3(i))C(B2(j))C(B2(i))¯C(B1(j))¯.

    Symmetric to C6.

  • 9. Level 2 Intersection: C9=CpathC(B2(i))C(B2(j))C(B1(i))¯C(B1(j))¯.

    Colors on the path present in both Level 2 blocks, excluding both Level 1 blocks.

  • 10. Local Colors: C10=Cpath(C(B1(i))C(B1(j))).

    Colors on the path present in the smallest (Level 1) blocks of either endpoint.

In the subsequent analysis, we will omit the subtasks marked as symmetric to others (e.g., C4, C7, C8), as their solutions are algorithmically identical to their counterparts, differing only in orientation.

For each of the subtasks 4-9, we will identify sets of candidate nodes of size O(t2), together with the corresponding endpoints l,r, and add them to the set S2. For subtasks 13 and 10, we will identify sets of candidates of size O(t1) or O(1), and add them to S1. At the end, we process the sets S2 and S1, in time O(|S2|)=O(t2) and O(|S1|loglogn)=O(t1loglogn), respectively, and return the color with the largest g-value. Since t1loglogn=t2, processing S1 and S2 takes O(t2) in total.

5.1.1 Proof of Completeness

We prove that these subtasks partition Cpath. Consider any color cCpath. Based on the block hierarchy, we can determine the membership of c in the color sets of the blocks surrounding i and j. Let Pu be the proposition cC(B3(u)) and Qu be the proposition cC(B2(u)) for u{i,j}. Since B2(u)B3(u), we have QuPu. The definitions of C1 through C9 correspond precisely to the disjoint logical conjunctions of these propositions (e.g., C2 corresponds to Pi¬Qi¬Pj). The set C10 captures the remaining cases where the color is present in C(B1(i)) or C(B1(j)). Thus, every color cCpath satisfies exactly one of these conditions, ensuring that k=110Ck=Cpath and all Ck are disjoint.

6 Solving the Subtasks

In this section, we present the algorithmic solutions for the subtasks defined previously. While the query procedures are concise, the precomputation strategies vary in complexity across subtasks; we sketch the data structures here, deferring full construction details to the full version of this paper [14]. We first state a key result from Durocher et al. [10] that enables efficient verification for our primary candidate set S1.

Lemma 10 (Durocher et al. [10]).

There exists an O(n)-space data structure that supports lowest colored ancestor queries on trees in O(loglogn) time.

To verify any cS1, we must evaluate g(i,j,c), which requires identifying the first and last occurrences of c on P(i,j). Using the lowest colored ancestor structure from Lemma 10, we locate these endpoints in O(loglogn) time, and compute g in O(1).

We analyze the space complexity, query time, and preprocessing time for each subtask. Note that any candidate color identified in these subtasks is added to the candidate set S1 (verification taking O(loglogn) time) or S2 (verification taking O(1) time), as per the strategy in Section 5.

6.1 Solving Subtask 1: The Global Region

We precompute a table T of size O((n/t3)2), indexed by the identifiers of the blocks in t3. For every pair of blocks Bu,Bvt3 with representatives u,v, the entry T[u][v] stores the color c that maximizes g(u,v,c), restricted to colors appearing on the path P(u,v) but not in C(Bu)C(Bv). During a query, we identify the blocks u=B3(i) and v=B3(j), retrieve the candidate c=T[u][v] in O(1) time, and add it to the primary candidate set S1. The table construction requires O(n(n/t3)) preprocessing time and O((n/t3)2) space, measured in words.

Complexity.

Preprocessing O(n(n/t3)); Space O((n/t3)2) words; Query Time O(1).

6.2 Solving Subtask 2: The Level 3 Ascent

We employ a lookup table T of size O(nt2nt3), indexed by pairs (u,v) representing a Level 2 block and a Level 3 block. The entry T[u][v] stores the relative index (using O(loglogn) bits) of a specific Level 1 block (or t1-node) inside B3(i) that contains at least one occurrence of the optimal color. During a query, we iterate through every distinct color c in this retrieved t1-node’s subtree and add each to S1.

Complexity.

Preprocessing O(n(n/t3)); Space O((n/t3)(n/t2)loglogn) bits; Query Time O(t1).

6.3 Solving Subtask 3: The Level 2 Ascent

This solution is analogous to Subtask 2. We use a table T of size O(nt1nt3). For a pair of blocks Bu, Bv (Level 1 and Level 3), T[u][v] stores the index of a t1-node inside B2(u) containing the optimal color. All colors in that t1-node are added to S1.

Complexity.

Preprocessing O(n(n/t3)); Space O((n/t3)(n/t1)loglogn) bits; Query Time O(t1).

6.4 Prerequisites for Subtasks 5, 6 and 9

To efficiently solve the intersection subtasks, we require advanced data structures that allow us to locate specific color occurrences within the block hierarchy in constant time. We refer to trees with size bounded by s=logn8loglogn as small trees.

Lemma 11.

There exists an O(n)-space data structure, constructible in O(n) time, that answers the following query in O(1) time: Given a small tree τ, a binary string σ of length |V(τ)|, and a node uV(τ), return the lowest ancestor of u marked with 1 in σ. If no such ancestor exists, return a marked node v such that no ancestor of v (other than potentially u) is marked.

Proof.

We employ the tabulation method. We precompute answers for all possible canonical instances of small trees. The number of distinct rooted trees with size up to s is bounded by O(2slogs). For each tree topology τ, there are 2|V(τ)|2s possible bitstrings σ. Thus, the total number of distinct query inputs (τ,σ,u) is bounded by:

O(2slogs2ss)=O(22loglognlogn8loglognlogn)=O(n1/4logn)O(n).

We construct a lookup table T indexed by the canonical ID of τ, the bitstring σ, and the node index u. We populate T using a standard DFS traversal for each instance. During the query phase, we map the input small tree to its canonical ID and retrieve the answer from T in O(1) time. The total space and preprocessing time are sublinear.

Lemma 12.

Given a colored tree 𝒯 and blocking factors t1<t2 with t2/t1=O(logn), there exists a linear-space perfect hashing structure (preprocessed in O(n) expected time) that answers the following in O(1) time: Given color c and t2-block B, return a binary string σ of length t2/t1 indicating which t1-blocks inside B contain c.

Proof.

We construct a dictionary of valid pairs. Let S be the set of triples (c,B,σ), where c is a color present in the t2-block B, and σ is the bitmask of length t2/t1 representing the presence of c in the constituent t1-blocks. The size of S is bounded by O(n) because each node in 𝒯 belongs to exactly one t1-block, contributing exactly one bit to one mask in the entire structure. We store S using a static perfect hashing scheme (e.g., Fredman, Komlós and Szemerédi [11], Hagerup and Torben [12], or Belazzougui, Botelho and Dietzfelbinger [1]), allowing O(1) worst-case lookups to retrieve σ for a pair (c,B), or returning null if cC(B).

Combining these lemmas with the block tree definitions, we obtain the following result for locating path endpoints.

Corollary 13.

There exists a linear-space data structure that, given endpoints i,j, blocks Bk(i),Bk(j) (k,k{2,3}), and a color c present in the blocks but not in their predecessors Bk1(i),Bk1(j), determines the first occurrence of c on the path P(i,j) in O(1) time.

Proof.

We assume the data structures from Lemmas 11 and 12 are constructed. Without loss of generality, we focus on finding the first occurrence of c in Bk(i) closest to i.

First, we query the hashing structure from Lemma 12 with (c,Bk(i)) to retrieve the bitmask σ. Treating the hierarchy of tk1-blocks inside Bk(i) as a small tree τ, we use the structure from Lemma 11 with start node u=Bk1(i) to find the lowest marked ancestor block bk1. This block is the tk1-block closest to Bk1(i) that contains c.

We distinguish two cases based on the topological relationship between Bk1(i) and bk1, as illustrated in Figure 3.

(a) Case 1 (b) Case 2
Figure 3: The two possible cases for the node bk1. The block marked with gray is the block Bk1(i). Blocks containing color c are marked with black, while the blocks that don’t contain c are marked with white. The block representatives are marked as a point in the center of a block circle. In (a), Case 1 is presented, where bk1 is not an ancestor of Bk1(i). In (b), Case 2 is presented, where bk1 is an ancestor of Bk1(i).
Case 1: 𝒃𝒌𝟏 is not an ancestor of 𝑩𝒌𝟏(𝒊).

Here, the path to c must pass through the LCA of the blocks. We maintain a precomputed table storing the topmost occurrence of every color c in every tk1-block. Let this node be vtop. We compute the immediate colored ancestor of vtop, denoted canc. If c is a proper ancestor of LCA(i,j), we locate the first occurrence by finding the occurrence on the path from j (say c) and performing a level ancestor query for the node at distance depth(c)depth(canc)1. To solve this case, we require an additional linear-space perfect hashing data structure to determine the topmost occurrence of a color c inside a block.

Case 2: 𝒃𝒌𝟏 is an ancestor of 𝑩𝒌𝟏(𝒊).

Here, the path traverses intermediate blocks that do not contain c. By the LCA Closure property, the relevant occurrence lies on an edge connecting blocks. We maintain a secondary perfect hashing structure storing pairs (c,β), where β is a block that does not contain c, but the edge connecting β to its parent block contains an occurrence of c. If bk1 is the found block, we compute the depth difference δ between Bk1(i) and bk1, jump to the (δ1)-th ancestor block bk1 (the child of bk1 on the path), and query the secondary hash table for (c,bk1) to find the occurrence on the entering edge.

The perfect hashing data structure for determining the occurrence of color c on the edge from a block β to its parent block, requires additional O(n+c𝒯countc) words of space, because each occurrence of a color c, appears in at most one path connecting β to its parent block, according to the LCA Closure property.

We must note that the same approach, with slight modifications, can be used to determine the desired nodes at which a color c occurs, even in the degenerate case, where the block Bk(i) is an ancestor of Bk(j) or vice versa.

6.5 Solving Subtask 5: Level 3 Intersection

We apply a stratified blocking approach. We define a sequence of blocking factors s0,,s|s| such that s0=t3, s|s|=t2, and sk+1=t2(log(sk/t2))2. Note that |s|=O(log(t3/t2)).

For each blocking factor sk, let sk be the set of sk blocks which partitions V(𝒯). For an sk block Bsk, let LB denote the list of all nodes from V(𝒯), contained inside block B, ordered in increasing order of the node index. We construct tables Tk for each level sk. For every configuration of blocks (Bsk(i),Bsk(j)), we store the approximate position (using the most significant 2log(sk/t2) bits) of the optimal color c within the linearized list of nodes of the blocks Bsk(i),Bsk(j). The total space required is:

k=0|s|(nsk)22log(skt2)=(nt2)2k=0|s|2logrkrk2=O((nt2)2) bits,

where rk=sk/t2. The query iterates through O(t2) candidate colors suggested by these tables. For each candidate c, we verify it is in C(B3)C(B2)¯ using Lemma 12 in O(1) time, find its endpoints l,r using Corollary 13, and add (c,l,r) to S2.

6.6 Solving Subtasks 6, 9, and 10

Subtask 6 (Mixed Level 2/3).

We iterate through all cC(B2(i)). We verify membership in the target set C6 using Lemma 12 and find endpoints (l,r) using Corollary 13, all in O(1) per color. Valid triplets are added to S2. The complexity is dominated by the size of B2(i), i.e., O(t2).

Subtask 9 (Level 2 Intersection).

Analogous to Subtask 6; runtime is O(t2).

Subtask 10 (Local).

We iterate through every color in C(B1(i))C(B1(j)) and add them directly to S1 (verified in O(loglogn)). The cost is O(t1).

Finally, to determine the actual answer to the query, we need to iterate through the colors inside S1, find their endpoints on the path P(i,j) by using the O(loglogn) time query from Lemma 10, and compute the associated value of g. Then, we iterate through the triplets (c,l,r)S2, and compute g(c,l,r). The answer to the query for the path P(i,j) is the color corresponding to the maximum value of g computed in this step.

Processing S2 will take O(|S2|)=O(t2) time, and processing S1 will take O(|S1|loglogn)=O(t1loglogn) time. Since t1loglogn=t2, the total time of processing the sets of candidates S2 and S1 is O(t2).

We will present the preprocessing algorithms and analyze their respective runtime for each data structure in the full version of this paper [14]. Now we only mention that a preprocessing runtime of O(n(n/t2))=O(nnt1loglogn) can be achieved. The total space required by our data structure is O((n/t2)2) bits. By substituting t2 by t, we formalize our result as follows.

Lemma 14.

Given a colored tree 𝒯, of n nodes, a function g respecting the properties from Section 2, and a blocking factor t, there exists a data structure, supporting path maximum g-value color queries in O(t) time, requiring O((nt)2) space in bits, and an O(n(n/t)) preprocessing time.

By setting t1=n/wloglogn, while keeping the values of t2 and t3 the same as a function of t1, we conclude this section with our main result directly following Lemma 14.

Theorem 15.

Given a colored tree 𝒯, of n nodes, a function g respecting the properties from Section 2, there exists a linear-space data structure, supporting path maximum g-value color queries in O(n/w) time, requiring an O(nnw) preprocessing time.

7 Faster Path 𝜶-Minority Queries on Trees

An α-minority in a multiset A, for some parameter α[0,1], is defined as an element that occurs at least once in A but constitutes no more than an α fraction of the total size of A. The path α-minority query for a tree path (u,v) asks to report any single color that occurs at most an α fraction of the tree path between nodes u and v. Durocher et al. [10] introduced a linear-space data structure capable of answering path α-minority queries on trees in O(α1loglogn) time, where the parameter α is specified at query time, and can differ for every query. In this section, we show that by incorporating randomness, the query time can be improved to O(α1) for a Monte Carlo algorithm (success probability 1/2) and to expected O(α1+loglogn) for a Las Vegas algorithm (success probability 1).

7.1 𝑶(𝜶𝟏) Time Algorithm with Success Probability 𝟏/𝟐

We use the following result from Durocher et al. [10] to efficiently retrieve candidate colors near the endpoints of the path.

Lemma 16 (Durocher et al. [10]).

There exists an O(n)-space data structure that supports k-nearest distinct ancestor queries on trees in O(k) time. The query returns the k distinct colors closest to a node u on the path to the root, in order of increasing distance.

Let P(i,j) be the query path, and let w=LCA(i,j). We define the length of the path as N=|P(i,j)|. We propose the following 4-phase query algorithm:

  • Phase 1 (Candidate Collection): We retrieve the sets of distinct colors closest to the endpoints. Let k=2α1.

    Sl the k distinct colors on P(i,w) closest to i.
    Sr the k distinct colors on P(j,w) closest to j.

    Note that if the path segment P(i,w) contains fewer than k distinct colors, Sl will simply contain all distinct colors on that segment (and similarly for Sr).

  • Phase 2 (Pruning Majorities): We remove obvious majorities. For each cSl, if the frequency of c on the sub-path P(i,w) exceeds αN, we remove c from Sl. We perform the symmetric check for Sr on P(j,w). This is valid because if a color is a majority on a sub-path with frequency exceeding the threshold for the entire path, it is certainly an α-majority for the whole path.

  • Phase 3 (Exact Verification of Overlap): Identify colors cSlSr. For these colors, we have identified both their first occurrence from i and their first occurrence from j. Since the sets Sl and Sr are built searching inwards from the endpoints, if c appears in both, we have bounded its occurrences. We can compute the exact frequency of c on P(i,j) in O(1) time (using the precomputed frequency data structures). If the frequency is αN, we return c immediately as the answer. We remove all colors cSlSr from Sl and Sr respectively. Thus, at the end of this phase, SlSr=.

  • Phase 4 (Random Sampling): If no answer was returned in Phase 3, we construct the set of remaining candidates D=SlSr. We select a color c uniformly at random from D and return it.

Lemma 17.

The query algorithm returns an α-minority in O(α1) time with probability 12.

Proof.

The time complexity is dominated by the retrieval of O(α1) colors and the set operations, which take O(α1) time. The frequency checks in Phase 2 and 3 take O(1) using the standard Level Ancestor and precomputed depth/frequency arrays (as employed in the virtual tree structures).

We analyze the success probability in two cases:

  1. 1.

    Case 1: The path has few distinct colors. Suppose the number of distinct colors on P(i,j) is at most 22α1. In this scenario, Sl and Sr effectively cover the entire path. Any color present on the path is in SlSr. Specifically, any α-minority is in this set. Thus, the algorithm succeeds with probability 1.

  2. 2.

    Case 2: The path has many distinct colors. Suppose there are more than 22α1 distinct colors. The number of α-majorities (colors with frequency >αN) is strictly less than α1. Our candidate set D=SlSr has size up to 22α14α1. Even in the worst case where every α-majority is present in D, there are at most α1 “bad” candidates. The number of “good” candidates (α-minorities) in D is at least |D|α13α1. Therefore, the probability of selecting an α-minority at random is at least: 3α14α1=3412.

7.2 Expected 𝑶(𝜶𝟏+𝐥𝐨𝐠𝐥𝐨𝐠𝒏) Time Algorithm

To achieve a success probability of 1, we extend Phase 4 into a Las Vegas algorithm. Instead of returning the random candidate immediately, we verify it. We can determine the exact endpoints of c on P(i,j) using an O(loglogn)-time predecessor/successor query (using the structure from Lemma 10). Once the endpoints are known, calculating the frequency takes O(1) time. We repeatedly pick a color c at random from SlSr, and verify its frequency, until an α-minority is found.

Since the probability of success in one sampling step is at least 1/2, the number of trials follows a geometric distribution with success parameter p1/2. The expected number of trials is at most 2. The total expected time complexity is: O(α1)+E[trials]O(loglogn)=O(α1+loglogn).

References

  • [1] Djamal Belazzougui, Fabiano C Botelho, and Martin Dietzfelbinger. Hash, displace, and compress. In European Symposium on Algorithms, pages 682–693. Springer, 2009. doi:10.1007/978-3-642-04128-0_61.
  • [2] Michael A Bender and Martin Farach-Colton. The lca problem revisited. In Latin American Symposium on Theoretical Informatics, pages 88–94. Springer, 2000. doi:10.1007/10719839_9.
  • [3] Michael A Bender and Martın Farach-Colton. The level ancestor problem simplified. Theoretical Computer Science, 321(1):5–12, 2004. doi:10.1016/J.TCS.2003.05.002.
  • [4] Omer Berkman and Uzi Vishkin. Recursive star-tree parallel data structure. SIAM Journal on Computing, 22(2):221–242, 1993. doi:10.1137/0222017.
  • [5] Omer Berkman and Uzi Vishkin. Finding level-ancestors in trees. Journal of computer and System Sciences, 48(2):214–230, 1994. doi:10.1016/S0022-0000(05)80002-9.
  • [6] Timothy M Chan, Stephane Durocher, Kasper Green Larsen, Jason Morrison, and Bryan T Wilkinson. Linear-space data structures for range mode query in arrays. Theory of Computing Systems, 55(4):719–741, 2014. doi:10.1007/S00224-013-9455-2.
  • [7] Timothy M Chan, Stephane Durocher, Matthew Skala, and Bryan T Wilkinson. Linear-space data structures for range minority query in arrays. In Scandinavian Workshop on Algorithm Theory, pages 295–306. Springer, 2012. doi:10.1007/978-3-642-31155-0_26.
  • [8] Bernard Chazelle. Filtering search: A new approach to query-answering. SIAM Journal on Computing, 15(3):703–724, 1986. doi:10.1137/0215051.
  • [9] Paul F Dietz. Finding level-ancestors in dynamic trees. In Workshop on Algorithms and Data Structures, pages 32–40. Springer, 1991. doi:10.1007/BFB0028247.
  • [10] Stephane Durocher, Rahul Shah, Matthew Skala, and Sharma V Thankachan. Linear-space data structures for range frequency queries on arrays and trees. Algorithmica, 74:344–366, 2016. doi:10.1007/S00453-014-9947-8.
  • [11] Michael L. Fredman, János Komlós, and Endre Szemerédi. Storing a sparse table with 0(1) worst case access time. J. ACM, 31(3):538–544, June 1984. doi:10.1145/828.1884.
  • [12] Torben Hagerup and Torsten Tholey. Efficient minimal perfect hashing in nearly minimal space. In STACS 2001: 18th Annual Symposium on Theoretical Aspects of Computer Science Dresden, Germany, February 15–17, 2001 Proceedings 18, pages 317–326. Springer, 2001. doi:10.1007/3-540-44693-1_28.
  • [13] Danny Krizanc, Pat Morin, and Michiel Smid. Range mode and range median queries on lists and trees. Nordic Journal of Computing, 12(1):1–17, 2005.
  • [14] Ovidiu Rata. Faster linear-space data structures for path frequency queries, 2026. arXiv:2604.18667.
  • [15] Matthew Skala. Array Range Queries, pages 333–350. Springer Berlin Heidelberg, Berlin, Heidelberg, 2013. doi:10.1007/978-3-642-40273-9_21.