Range query (data structures)

In data structures, a range query consists of pre-processing some input data into a data structure to efficiently answer any number of queries on any subset of the input. Particularly, there is a group of problems that have been extensively studied where the input is an array of unsorted numbers and a query consists of computing some function, such as the minimum, on a specific range of the array.

## Contents

* 1 Definition
* 2 Examples
* 2.1 Semigroup operators
* 2.2 Mode
* 2.3 Median
* 2.4 Majority
* 2.4.1 Two-dimensional arrays
* 2.4.2 One-dimensional arrays
* 2.4.3 Tree paths
* 3 Related problems
* 4 See also
* 5 References
* 6 External links

## Definition

A range query qf(A,i,j) on an array A=[a1,a2,..,an] of n elements of some set S, denoted A[1,n], takes two indices 1≤i≤j≤n, a function f defined over arrays of elements of S and outputs f(A[i,j])=f(ai,…,aj).

For example, for f=∑ and A[1,n] an array of numbers, the range query ∑i,jA computes ∑A[i,j]=(ai+…+aj), for any 1≤i≤j≤n. These queries may be answered in constant time and using O(n) extra space by calculating the sums of the first i elements of A and storing them into an auxiliary array B, such that B[i] contains the sum of the first i elements of A for every 0≤i≤n. Therefore, any query might be answered by doing ∑A[i,j]=B[j]−B[i−1].

This strategy may be extended for every group operator f where the notion of f−1 is well defined and easily computable.[1] Finally, this solution can be extended to two-dimensional arrays with a similar pre-processing.[2]

## Examples

### Semigroup operators

Range minimum query reduced to the lowest common ancestor problem.

Main article: Range minimum query

When the function of interest in a range query is a semigroup operator, the notion of f−1 is not always defined, so the strategy in the previous section does not work. Andrew Yao showed[3] that there exists an efficient solution for range queries that involve semigroup operators. He proved that for any constant c, a pre-processing of time and space θ(c⋅n) allows to answer range queries on lists where f is a semigroup operator in θ(αc(n)) time, where αc is a certain functional inverse of the Ackermann function.

There are some semigroup operators that admit slightly better solutions. For instance when f∈{max⁡,min⁡}. Assume f=min then min⁡(A[1..n]) returns the index of the minimum element of A[1..n]. Then mini,j(A) denotes the corresponding minimum range query. There are several data structures that allow to answer a range minimum query in O(1) time using a pre-processing of time and space O(n). One such solution is based on the equivalence between this problem and the lowest common ancestor problem.

The Cartesian tree TA of an array A[1,n] has as root ai=min⁡{a1,a2,…,an} and as left and right subtrees the Cartesian tree of A[1,i−1] and the Cartesian tree of A[i+1,n] respectively. A range minimum query mini,j(A) is the lowest common ancestor in TA of ai and aj. Because the lowest common ancestor can be solved in constant time using a pre-processing of time and space O(n), range minimum query can as well. The solution when f=max is analogous. Cartesian trees can be constructed in linear time.

### Mode

Main article: Range mode query

The mode of an array A is the element that appears the most in A. For instance the mode of A=[4,5,6,7,4] is 4. In case of ties any of the most frequent elements might be picked as mode. A range mode query consists in pre-processing A[1,n] such that we can find the mode in any range of A[1,n]. Several data structures have been devised to solve this problem, we summarize some of the results in the following table.[1]

Range Mode Queries  Space | Query Time | Restrictions

|
|

O(n2−2ϵ) | O(nϵlog⁡n) | 0≤ϵ≤12
O(n2log⁡log⁡nlog⁡n) | O(1) |

Recently Jørgensen et al. proved a lower bound on the cell-probe model of Ω(log⁡nlog⁡(Sw/n)) for any data structure that uses S cells.[4]

### Median

This particular case is of special interest since finding the median has several applications.[5] On the other hand, the median problem, a special case of the selection problem, is solvable in O(n), using the median of medians algorithm.[6] However its generalization through range median queries is recent.[7] A range median query median⁡(A,i,j) where A,i and j have the usual meanings returns the median element of A[i,j]. Equivalently, median⁡(A,i,j) should return the element of A[i,j] of rank j−i2. Range median queries cannot be solved by following any of the previous methods discussed above including Yao's approach for semigroup operators.[8]

There have been studied two variants of this problem, the offline version, where all the k queries of interest are given in a batch, and a version where all the pre-processing is done up front. The offline version can be solved with O(nlog⁡k+klog⁡n) time and O(nlog⁡k) space.

The following pseudocode of the quickselect algorithm shows how to find the element of rank r in A[i,j] an unsorted array of distinct elements, to find the range medians we set r=j−i2.[7]

rangeMedian(A, i, j, r) {
if A.length() == 1
return A[1]

if A.low is undefined then
m = median(A)
A.low  = [e in A | e <= m]
A.high = [e in A | e > m ]

calculate t the number of elements of A[i, j] that belong to A.low

if r <= t then
return rangeMedian(A.low, i, j, r)
else
return rangeMedian(A.high, i, j, r-t)

Procedure `rangeMedian` partitions `A`, using `A`'s median, into two arrays `A.low` and `A.high`, where the former contains the elements of `A` that are less than or equal to the median `m` and the latter the rest of the elements of `A`. If we know that the number of elements of A[i,j] that end up in `A.low` is `t` and this number is bigger than `r` then we should keep looking for the element of rank `r` in `A.low`; otherwise we should look for the element of rank (r−t) in `A.high`. To find t, it is enough to find the maximum index m≤i−1 such that am is in `A.low` and the maximum index l≤j such that al is in `A.high`. Then t=l−m. The total cost for any query, without considering the partitioning part, is log⁡n since at most log⁡n recursion calls are done and only a constant number of operations are performed in each of them (to get the value of t fractional cascading should be used). If a linear algorithm to find the medians is used, the total cost of pre-processing for k range median queries is nlog⁡k. The algorithm can also be modified to solve the online version of the problem.[7]

### Majority

Finding frequent elements in a given set of items is one of the most important tasks in data mining. Finding frequent elements might be a difficult task to achieve when most items have similar frequencies. Therefore, it might be more beneficial if some threshold of significance was used for detecting such items. One of the most famous algorithms for finding the majority of an array was proposed by Boyer and Moore [9] which is also known as the Boyer–Moore majority vote algorithm. Boyer and Moore proposed an algorithm to find the majority element of a string (if it has one) in O(n) time and using O(1) space. In the context of Boyer and Moore’s work and generally speaking, a majority element in a set of items (for example string or an array) is one whose number of instances is more than half of the size of that set. Few years later, Misra and Gries [10] proposed a more general version of Boyer and Moore's algorithm using O(nlog⁡(1τ)) comparisons to find all items in an array whose relative frequencies are greater than some threshold 0<τ<1. A range τ-majority query is one that, given a subrange of a data structure (for example an array) of size |R|, returns the set of all distinct items that appear more than (or in some publications equal to) τ|R| times in that given range. In different structures that support range τ-majority queries, τ can be either static (specified during pre-processing) or dynamic (specified at query time). Many of such approaches are based on the fact that, regardless of the size of the range, for a given τ there could be at most O(1/τ) distinct candidates with relative frequencies at least τ. By verifying each of these candidates in constant time, O(1/τ) query time is achieved. A range τ-majority query is decomposable [11] in the sense that a τ-majority in a range R with partitions R1 and R2 must be a τ-majority in either R1or R2. Due to this decomposability, some data structures answer τ-majority queries on one-dimensional arrays by finding the Lowest common ancestor (LCA) of the endpoints of the query range in a Range tree and validating two sets of candidates (of size O(1/τ)) from each endpoint to the lowest common ancestor in constant time resulting in O(1/τ) query time.

#### Two-dimensional arrays

Gagie et al.[12] proposed a data structure that supports range τ-majority queries on an m×n array A. For each query Q⁡=(R⁡,τ) in this data structure a threshold 0<τ<1 and a rectangular range R are specified, and the set of all elements that have relative frequencies (inside that rectangular range) greater than or equal to τ are returned as the output. This data structure supports dynamic thresholds (specified at query time) and a pre-processing threshold α based on which it is constructed. During the pre-processing, a set of vertical and horizontal intervals are built on the m×n array. Together, a vertical and a horizontal interval form a block. Each block is part of a superblock nine times bigger than itself (three times the size of the block's horizontal interval and three times the size of its vertical one). For each block a set of candidates (with 9α elements at most) is stored which consists of elements that have relative frequencies at least α9 (the pre-processing threshold as mentioned above) in its respective superblock. These elements are stored in non-increasing order according to their frequencies and it is easy to see that, any element that has a relative frequency at least α in a block must appear its set of candidates. Each τ-majority query is first answered by finding the query block, or the biggest block that is contained in the provided query rectangle in O(1) time. For the obtained query block, the first 9τ candidates are returned (without being verified) in O(1/τ) time, so this process might return some false positives. Many other data structures (as discussed below) have proposed methods for verifying each candidate in constant time and thus maintaining the O(1/τ) query time while returning no false positives. The cases in which the query block is smaller than 1/α are handled by storing log⁡(1α) different instances of this data structure of the following form:

β=2−i,i∈{1,…,log⁡(1α)}

where β is the pre-processing threshold of the i-th instance. Thus, for query blocks smaller than 1/α the ⌈log⁡(1/τ)⌉-th instance is queried. As mentioned above, this data structure has query time O(1/τ) and requires O(mn(H+1)log2(1α)) bits of space by storing a Huffman-encoded copy of it (note the log⁡(1α) factor and also see Huffman coding).

#### One-dimensional arrays

Chan et al.[13] proposed a data structure that given a one-dimensional arrayA, a subrange R of A (specified at query time) and a threshold τ (specified at query time), is able to return the list of all τ-majorities in O(1/τ) time requiring O(nlog⁡n) words of space. To answer such queries, Chan et al.[13] begin by noting that there exists a data structure capable of returning the top-k most frequent items in a range in O(k) time requiring O(n) words of space. For a one-dimensional array A[0,..,n−1], let a one-sided top-k range query to be of form A[0..i] for 0≤i≤n−1. For a maximal range of ranges A[0..i] through A[0..j] in which the frequency of a distinct element e in A remains unchanged (and equal to f), a horizontal line segment is constructed. The x-interval of this line segment corresponds to [i,j] and it has a y-value equal to f. Since adding each element to A changes the frequency of exactly one distinct element, the aforementioned process creates O(n) line segments. Moreover, for a vertical line x=i all horizonal line segments intersecting it are sorted according to their frequencies. Note that, each horizontal line segment with x-interval [ℓ,r] corresponds to exactly one distinct element e in A, such that A[ℓ]=e. A top-k query can then be answered by shooting a vertical ray x=i and reporting the first k horizontal line segments that intersect it (remember from above that these line line segments are already sorted according to their frequencies) in O(k) time.

Chan et al.[13] first construct a range tree in which each branching node stores one copy of the data structure described above for one-sided range top-k queries and each leaf represents an element from A. The top-k data structure at each node is constructed based on the values existing in the subtrees of that node and is meant to answer one-sided range top-k queries. Please note that for a one-dimensional array A, a range tree can be constructed by dividing A into two halves and recursing on both halves; therefore, each node of the resulting range tree represents a range. It can also be seen that this range tree requires O(nlog⁡n) words of space, because there are O(log⁡n) levels and each level ℓ has 2ℓ nodes. Moreover, since at each level ℓ of a range tree all nodes have a total of n elements of A at their subtrees and since there are O(log⁡n) levels, the space complexity of this range tree is O(nlog⁡n).

Using this structure, a range τ-majority query A[i..j] on A[0..n−1] with 0≤i≤j≤n is answered as follows. First, the lowest common ancestor (LCA) of leaf nodes i and j is found in constant time. Note that there exists a data structure requiring O(n) bits of space that is capable of answering the LCA queries in O(1) time.[14] Let z denote the LCA of i and j, using z and according to the decomposability of range τ-majority queries (as described above and in [11]), the two-sided range query A[i..j] can be converted into two one-sided range top-k queries (from z to i and j). These two one-sided range top-k queries return the top-(1/τ) most frequent elements in each of their respective ranges in O(1/τ) time. These frequent elements make up the set of candidates for τ-majorities in A[i..j] in which there are O(1/τ) candidates some of which might be false positives. Each candidate is then assessed in constant time using a linear-space data structure (as described in Lemma 3 in [15]) that is able to determine in O(1) time whether or not a given subrange of an array A contains at least q instances of a particular element e.

#### Tree paths

Gagie et al.[16] proposed a data structure which supports queries such that, given two nodes u and v in a tree, are able to report the list of elements that have a greater relative frequency than τ on the path from u to v. More formally, let T be a labelled tree in which each node has a label from an alphabet of size σ. Let label(u)∈[1,…,σ] denote the label of node u in T. Let Puv denote the unique path from u to v in T in which middle nodes are listed in the order they are visited. Given T, and a fixed (specified during pre-processing) threshold 0<τ<1, a query Q(u,v) must return the set of all labels that appear more than τ|Puv| times in Puv.

To construct this data structure, first O(τn) nodes are marked. This can be done by marking any node that has distance at least ⌈1/τ⌉ from the bottom of the three (height) and whose depth is divisible by ⌈1/τ⌉. After doing this, it can be observed that the distance between each node and its nearest marked ancestor is less than 2⌈1/τ⌉. For a marked node x, log⁡(depth(x)) different sequences (paths towards the root) Pi(x) are stored,

Pi(x)=⟨label⁡(x),par⁡(x),par2(x),…,par2i(x)⟩

for 0≤i≤log⁡(depth(x)) where par⁡(x) returns the label of the direct parent of node x. Put another way, for each marked node, the set of all paths with a power of two length (plus one for the node itself) towards the root is stored. Moreover, for each Pi(x), the set of all majority candidates Ci(x) are stored. More specifically, Ci(x) contains the set of all (τ/2)-majorities in Pi(x) or labels that appear more than (τ/2).(2i+1) times in Pi(x). It is easy to see that the set of candidates Ci(x) can have at most 2/τ distinct labels for each i. Gagie et al.[16] then note that the set of all τ-majorities in the path from any marked node x to one of its ancestors z is included in some Ci(x) (Lemma 2 in [16]) since the length of Pi(x) is equal to (2i+1) thus there exists a Pi(x) for 0≤i≤log⁡(depth(x)) whose length is between dxz and 2dxz where dxz is the distance between x and z. The existence of such Pi(x) implies that a τ-majority in the path from x to z must be a (τ/2)-majority in Pi(x), and thus must appear in Ci(x). It is easy to see that this data structure require O(nlog⁡n) words of space, because as mentioned above in the construction phase O(τn) nodes are marked and for each marked node some candidate sets are stored. By definition, for each marked node O(log⁡n) of such sets are stores, each of which contains O(1/τ) candidates. Therefore, this data structure requires O(log⁡n×(1/τ)×τn)=O(nlog⁡n) words of space. Please note that each node x also stores count(x) which is equal to the number of instances of label(x) on the path from x to the root of T, this does not increase the space complexity since it only adds a constant number of words per node.

Each query between two nodes u and v can be answered by using the decomposability property (as explained above) of range τ-majority queries and by breaking the query path between u and v into four subpaths. Let z be the lowest common ancestor of u and v, with x and y being the nearest marked ancestors of u and v respectively. The path from u to v is decomposed into the paths from u and v to x and y respectively (the size of these paths are smaller than 2⌈1/τ⌉ by definition, all of which are considered as candidates), and the paths from x and y to z (by finding the suitable Ci(x) as explained above and considering all of its labels as candidates). Please note that, boundary nodes have to be handled accordingly so that all of these subpaths are disjoint and from all of them a set of O(1/τ) candidates is derived. Each of these candidates is then verified using a combination of the labelanc(x,ℓ) query which returns the lowest ancestor of node x that has label ℓ and the count(x) fields of each node. On a w-bit RAM and an alphabet of size σ, the labelanc(x,ℓ) query can be answered in O(log⁡logwσ) time whilst having linear space requirements.[17] Therefore, verifying each of the O(1/τ) candidates in O(log⁡logwσ) time results in O((1/τ)log⁡logwσ) total query time for returning the set of all τ-majorities on the path from u to v.

## Related problems

All the problems described above have been studied for higher dimensions as well as their dynamic versions. On the other hand, range queries might be extended to other data structures like trees,[8] such as the level ancestor problem. A similar family of problems are orthogonal range queries, also known as counting queries.

## See also

* Level ancestor problem
* Lowest common ancestor

## References

1. ↑ 1.0 1.1 Krizanc, Danny; Morin, Pat; Smid, Michiel H. M. (2003). "Range Mode and Range Median Queries on Lists and Trees". ISAAC: 517–526. Bibcode: 2003cs........7034K. http://cg.scs.carleton.ca/~morin/publications/.
2. ↑ Meng, He; Munro, J. Ian; Nicholson, Patrick K. (2011). "Dynamic Range Selection in Linear Space". ISAAC: 160–169.
3. ↑ Yao, A. C (1982). "Space-Time Tradeoff for Answering Range Queries". E 14th Annual ACM Symposium on the Theory of Computing: 128–136.
4. ↑ Greve, M; J{\o}rgensen, A.; Larsen, K.; Truelsen, J. (2010). "Cell probe lower bounds and approximations for range mode". Automata, Languages and Programming: 605–616.
5. ↑ Har-Peled, Sariel; Muthukrishnan, S. (2008). "Range Medians". ESA: 503–514.
6. ↑ Blum, M.; Floyd, R. W.; Pratt, V. R.; Rivest, R. L.; Tarjan, R. E. (August 1973). "Time bounds for selection". Journal of Computer and System Sciences 7 (4): 448–461. doi:10.1016/S0022-0000(73)80033-9. http://people.csail.mit.edu/rivest/pubs/BFPRT73.pdf.
7. ↑ 7.0 7.1 7.2 Beat, Gfeller; Sanders, Peter (2009). "Towards Optimal Range Medians". Icalp (1): 475–486.
8. ↑ 8.0 8.1 Bose, P; Kranakis, E.; Morin, P.; Tang, Y. (2005). "Approximate range mode and range median queries". In Proceedings of the 22nd Symposium on Theoretical Aspects of Computer Science (STACS 2005), Volume 3404 of Lecture Notes in ComputerScience: 377–388. http://cg.scs.carleton.ca/~morin/publications/.
9. ↑ Boyer, Robert S.; Moore, J. Strother (1991), MJRTY—A Fast Majority Vote Algorithm, Automated Reasoning Series, 1, Dordrecht: Springer Netherlands, pp. 105–117, doi:10.1007/978-94-011-3488-0_5, ISBN 978-94-010-5542-0, http://dx.doi.org/10.1007/978-94-011-3488-0_5, retrieved 2021-12-18
10. ↑ Misra, J.; Gries, David (November 1982). "Finding repeated elements". Science of Computer Programming 2 (2): 143–152. doi:10.1016/0167-6423(82)90012-0. ISSN 0167-6423. http://dx.doi.org/10.1016/0167-6423(82)90012-0.
11. ↑ 11.0 11.1 Karpiński, Marek. Searching for frequent colors in rectangles. OCLC 277046650. http://worldcat.org/oclc/277046650.
12. ↑ Gagie, Travis; He, Meng; Munro, J. Ian; Nicholson, Patrick K. (2011), "Finding Frequent Elements in Compressed 2D Arrays and Strings", String Processing and Information Retrieval (Berlin, Heidelberg: Springer Berlin Heidelberg): pp. 295–300, doi:10.1007/978-3-642-24583-1_29, ISBN 978-3-642-24582-4, http://dx.doi.org/10.1007/978-3-642-24583-1_29, retrieved 2021-12-18
13. ↑ 13.0 13.1 13.2 Chan, Timothy M.; Durocher, Stephane; Skala, Matthew; Wilkinson, Bryan T. (2012), "Linear-Space Data Structures for Range Minority Query in Arrays", Algorithm Theory – SWAT 2012 (Berlin, Heidelberg: Springer Berlin Heidelberg): pp. 295–306, doi:10.1007/978-3-642-31155-0_26, ISBN 978-3-642-31154-3, http://dx.doi.org/10.1007/978-3-642-31155-0_26, retrieved 2021-12-20
14. ↑ Sadakane, Kunihiko; Navarro, Gonzalo (2010-01-17). "Fully-Functional Succinct Trees". Proceedings of the Twenty-First Annual ACM-SIAM Symposium on Discrete Algorithms (Philadelphia, PA: Society for Industrial and Applied Mathematics): 134–149. doi:10.1137/1.9781611973075.13. ISBN 978-0-89871-701-3. http://dx.doi.org/10.1137/1.9781611973075.13.
15. ↑ Chan, Timothy M.; Durocher, Stephane; Larsen, Kasper Green; Morrison, Jason; Wilkinson, Bryan T. (2013-03-08). "Linear-Space Data Structures for Range Mode Query in Arrays". Theory of Computing Systems 55 (4): 719–741. doi:10.1007/s00224-013-9455-2. ISSN 1432-4350. http://dx.doi.org/10.1007/s00224-013-9455-2.
16. ↑ 16.0 16.1 16.2 Gagie, Travis; He, Meng; Navarro, Gonzalo; Ochoa, Carlos (September 2020). "Tree path majority data structures". Theoretical Computer Science 833: 107–119. doi:10.1016/j.tcs.2020.05.039. ISSN 0304-3975. http://dx.doi.org/10.1016/j.tcs.2020.05.039.
17. ↑ He, Meng; Munro, J. Ian; Zhou, Gelin (2014-07-08). "A Framework for Succinct Labeled Ordinal Trees over Large Alphabets". Algorithmica 70 (4): 696–717. doi:10.1007/s00453-014-9894-4. ISSN 0178-4617. http://dx.doi.org/10.1007/s00453-014-9894-4.

## External links

* Open Data Structure - Chapter 13 - Data Structures for Integers
* Data Structures for Range Median Queries - Gerth Stolting Brodal and Allan Gronlund Jorgensen

* v
* t
* e

Tree data structures

Search trees
(dynamic sets/associative arrays)|

* 2–3
* 2–3–4
* AA
* (a,b)
* AVL
* B
* B+
* B*
* Bx
* (Optimal) Binary search
* Dancing
* HTree
* Interval
* Order statistic
* (Left-leaning) Red-black
* Scapegoat
* Splay
* T
* Treap
* UB
* Weight-balanced

Heaps|

* Binary
* Binomial
* Brodal
* Fibonacci
* Leftist
* Pairing
* Skew
* van Emde Boas
* Weak

Tries|

* Ctrie
* C-trie (compressed ADT)
* Hash
* Radix
* Suffix
* Ternary search
* X-fast
* Y-fast

Spatial data partitioning trees|

* Ball
* BK
* BSP
* Cartesian
* Hilbert R
* k-d (implicit k-d)
* M
* Metric
* MVP
* Octree
* Priority R
* Quad
* R
* R+
* R*
* Segment
* VP
* X

Other trees|

* Cover
* Exponential
* Fenwick
* Finger
* Fractal tree index
* Fusion
* Hash calendar
* iDistance
* K-ary
* Left-child right-sibling
* Link/cut
* Log-structured merge
* Merkle
* PQ
* Range
* SPQR
* Top

0.00

(0 votes)

|

Retrieved from "https://handwiki.org/wiki/index.php?title=Range_query_(data_structures)&oldid=314686"
*[v]: View this template
*[t]: Discuss this template
*[e]: Edit this template