|
1 |
| -/** |
2 |
| - * Segment Tree implementation for Range Query data structure |
3 |
| - * Tracks a array of numbers. 0 indexed |
4 |
| - * operation is a binary function (eg sum, min) - needs to be associative |
5 |
| - * identity is the identity of the operation |
6 |
| - * i.e, operation(x, identity) = x (eg 0 for sum, Infinity for min) |
7 |
| - * Supports methods |
8 |
| - * update(index, val) - set value of index |
9 |
| - * query(l, r) - finds operation(values in range [l, r]) (both inclusive) |
10 |
| - * |
11 |
| - * As is customary, we store the tree implicitly with i being the parent of 2i, 2i+1. |
12 |
| - */ |
| 1 | +importisPowerOfTwofrom'../../../algorithms/math/is-power-of-two/isPowerOfTwo'; |
13 | 2 |
|
14 | 3 | exportdefaultclassSegmentTree{
|
15 | 4 | /**
|
16 |
| - * array initialises the numbers |
17 |
| - *@param {number[]} array |
| 5 | + *@param {number[]} inputArray |
| 6 | + *@param {function} operation - binary function (i.e. sum, min) |
| 7 | + *@param {number} operationFallback - operation fallback value (i.e. 0 for sum, Infinity for min) |
18 | 8 | */
|
19 |
| -constructor(array,operation,identity){ |
20 |
| -this.n=array.length; |
21 |
| -this.array=array; |
22 |
| -this.tree=newArray(4*this.n); |
23 |
| - |
| 9 | +constructor(inputArray,operation,operationFallback){ |
| 10 | +this.inputArray=inputArray; |
24 | 11 | this.operation=operation;
|
25 |
| -this.identity=identity; |
26 |
| - |
27 |
| -// use Range Min Query by default |
28 |
| -if(this.operation===undefined){ |
29 |
| -this.operation=Math.min; |
30 |
| -this.identity=Infinity; |
31 |
| -} |
| 12 | +this.operationFallback=operationFallback; |
32 | 13 |
|
| 14 | +// Init array representation of segment tree. |
| 15 | +this.segmentTree=this.initSegmentTree(this.inputArray); |
33 | 16 |
|
34 |
| -this.build(); |
| 17 | +this.buildSegmentTree(); |
35 | 18 | }
|
36 | 19 |
|
37 | 20 | /**
|
38 |
| - * Stub for recursive call |
| 21 | + *@param {number[]} inputArray |
| 22 | + *@return {number[]} |
39 | 23 | */
|
40 |
| -build(){ |
41 |
| -this.buildRec(1,0,this.n-1); |
42 |
| -} |
| 24 | +initSegmentTree(inputArray){ |
| 25 | +letsegmentTreeArrayLength; |
| 26 | +constinputArrayLength=inputArray.length; |
43 | 27 |
|
44 |
| -/** |
45 |
| - * Left child index |
46 |
| - *@param {number} root |
47 |
| - */ |
48 |
| -left(root){ |
49 |
| -return2*root; |
| 28 | +if(isPowerOfTwo(inputArrayLength)){ |
| 29 | +// If original array length is a power of two. |
| 30 | +segmentTreeArrayLength=(2*inputArrayLength)-1; |
| 31 | +}else{ |
| 32 | +// If original array length is not a power of two then we need to find |
| 33 | +// next number that is a power of two and use it to calculate |
| 34 | +// tree array size. This is happens because we need to fill empty children |
| 35 | +// in perfect binary tree with nulls.And those nulls need extra space. |
| 36 | +constcurrentPower=Math.floor(Math.log2(inputArrayLength)); |
| 37 | +constnextPower=currentPower+1; |
| 38 | +constnextPowerOfTwoNumber=2**nextPower; |
| 39 | +segmentTreeArrayLength=(2*nextPowerOfTwoNumber)-1; |
| 40 | +} |
| 41 | + |
| 42 | +returnnewArray(segmentTreeArrayLength).fill(null); |
50 | 43 | }
|
51 | 44 |
|
52 | 45 | /**
|
53 |
| - * Right child index |
54 |
| - *@param {number} root |
| 46 | + * Build segment tree. |
55 | 47 | */
|
56 |
| -right(root){ |
57 |
| -return(2*root)+1; |
| 48 | +buildSegmentTree(){ |
| 49 | +constleftIndex=0; |
| 50 | +constrightIndex=this.inputArray.length-1; |
| 51 | +constposition=0; |
| 52 | +this.buildTreeRecursively(leftIndex,rightIndex,position); |
58 | 53 | }
|
59 | 54 |
|
60 | 55 | /**
|
61 |
| - * root is the index in the tree, [l,r] (inclusive) is the current array segment being built |
62 |
| - *@param {number} root |
63 |
| - *@param {number} l |
64 |
| - *@param {number} r |
| 56 | + * Build segment tree recursively. |
| 57 | + * |
| 58 | + *@param {number} leftInputIndex |
| 59 | + *@param {number} rightInputIndex |
| 60 | + *@param {number} position |
65 | 61 | */
|
66 |
| -buildRec(root,l,r){ |
67 |
| -if(l===r){ |
68 |
| -this.tree[root]=this.array[l]; |
69 |
| -}else{ |
70 |
| -constmid=Math.floor((l+r)/2); |
71 |
| -// build left and right nodes |
72 |
| -this.buildRec(this.left(root),l,mid); |
73 |
| -this.buildRec(this.right(root),mid+1,r); |
74 |
| -this.tree[root]=this.operation(this.tree[this.left(root)],this.tree[this.right(root)]); |
| 62 | +buildTreeRecursively(leftInputIndex,rightInputIndex,position){ |
| 63 | +// If low input index and high input index are equal that would mean |
| 64 | +// the we have finished splitting and we are already came to the leaf |
| 65 | +// of the segment tree. We need to copy this leaf value from input |
| 66 | +// array to segment tree. |
| 67 | +if(leftInputIndex===rightInputIndex){ |
| 68 | +this.segmentTree[position]=this.inputArray[leftInputIndex]; |
| 69 | +return; |
75 | 70 | }
|
| 71 | + |
| 72 | +// Split input array on two halves and process them recursively. |
| 73 | +constmiddleIndex=Math.floor((leftInputIndex+rightInputIndex)/2); |
| 74 | +// Process left half of the input array. |
| 75 | +this.buildTreeRecursively(leftInputIndex,middleIndex,this.getLeftChildIndex(position)); |
| 76 | +// Process right half of the input array. |
| 77 | +this.buildTreeRecursively(middleIndex+1,rightInputIndex,this.getRightChildIndex(position)); |
| 78 | + |
| 79 | +// Once every tree leaf is not empty we're able to build tree bottom up using |
| 80 | +// provided operation function. |
| 81 | +this.segmentTree[position]=this.operation( |
| 82 | +this.segmentTree[this.getLeftChildIndex(position)], |
| 83 | +this.segmentTree[this.getRightChildIndex(position)], |
| 84 | +); |
76 | 85 | }
|
77 | 86 |
|
78 | 87 | /**
|
79 |
| - * Stub for recursive call |
80 |
| - *@param {number} lindex |
81 |
| - *@param {number} rindex |
| 88 | + * Do range query on segment tree in context of this.operation function. |
| 89 | + * |
| 90 | + *@param {number} queryLeftIndex |
| 91 | + *@param {number} queryRightIndex |
| 92 | + *@return {number} |
82 | 93 | */
|
83 |
| -query(lindex,rindex){ |
84 |
| -returnthis.queryRec(1,lindex,rindex,0,this.n-1); |
| 94 | +rangeQuery(queryLeftIndex,queryRightIndex){ |
| 95 | +constleftIndex=0; |
| 96 | +constrightIndex=this.inputArray.length-1; |
| 97 | +constposition=0; |
| 98 | + |
| 99 | +returnthis.rangeQueryRecursive( |
| 100 | +queryLeftIndex, |
| 101 | +queryRightIndex, |
| 102 | +leftIndex, |
| 103 | +rightIndex, |
| 104 | +position, |
| 105 | +); |
85 | 106 | }
|
86 | 107 |
|
87 | 108 | /**
|
88 |
| - *[lindex, rindex] is the query region |
89 |
| - * [l,r] is the current region being processed |
90 |
| - *Guaranteed that [lindex,rindex] contained in [l,r] |
91 |
| - *@param {number}root |
92 |
| - *@param {number}lindex |
93 |
| - *@param {number}rindex |
94 |
| - *@param {number}l |
95 |
| - *@param {number} r |
| 109 | + *Do range query on segment tree recursively in context of this.operation function. |
| 110 | + * |
| 111 | + *@param {number} queryLeftIndex - left index of the query |
| 112 | + *@param {number}queryRightIndex - right index of the query |
| 113 | + *@param {number}leftIndex - left index of input array segment |
| 114 | + *@param {number}rightIndex - right index of input array segment |
| 115 | + *@param {number}position - root position in binary tree |
| 116 | + *@return {number} |
96 | 117 | */
|
97 |
| -queryRec(root,lindex,rindex,l,r){ |
98 |
| -// console.log(root, lindex, rindex, l, r); |
99 |
| -if(lindex>rindex){ |
100 |
| -// happens when mid+1 > r - no segment |
101 |
| -returnthis.identity; |
| 118 | +rangeQueryRecursive(queryLeftIndex,queryRightIndex,leftIndex,rightIndex,position){ |
| 119 | +if(queryLeftIndex<=leftIndex&&queryRightIndex>=rightIndex){ |
| 120 | +// Total overlap. |
| 121 | +returnthis.segmentTree[position]; |
102 | 122 | }
|
103 |
| -if(l===lindex&&r===rindex){ |
104 |
| -// query region matches current region - use tree value |
105 |
| -returnthis.tree[root]; |
| 123 | + |
| 124 | +if(queryLeftIndex>rightIndex||queryRightIndex<leftIndex){ |
| 125 | +// No overlap. |
| 126 | +returnthis.operationFallback; |
106 | 127 | }
|
107 |
| -constmid=Math.floor((l+r)/2); |
108 |
| -// get left and right results and combine |
109 |
| -constleftResult=this.queryRec(this.left(root),lindex,Math.min(rindex,mid),l,mid); |
110 |
| -constrightResult=this.queryRec( |
111 |
| -this.right(root),Math.max(mid+1,lindex),rindex, |
112 |
| -mid+1,r, |
| 128 | + |
| 129 | +// Partial overlap. |
| 130 | +constmiddleIndex=Math.floor((leftIndex+rightIndex)/2); |
| 131 | + |
| 132 | +constleftOperationResult=this.rangeQueryRecursive( |
| 133 | +queryLeftIndex, |
| 134 | +queryRightIndex, |
| 135 | +leftIndex, |
| 136 | +middleIndex, |
| 137 | +this.getLeftChildIndex(position), |
113 | 138 | );
|
114 |
| -returnthis.operation(leftResult,rightResult); |
| 139 | + |
| 140 | +constrightOperationResult=this.rangeQueryRecursive( |
| 141 | +queryLeftIndex, |
| 142 | +queryRightIndex, |
| 143 | +middleIndex+1, |
| 144 | +rightIndex, |
| 145 | +this.getRightChildIndex(position), |
| 146 | +); |
| 147 | + |
| 148 | +returnthis.operation(leftOperationResult,rightOperationResult); |
115 | 149 | }
|
116 | 150 |
|
117 | 151 | /**
|
118 |
| - *Set array[index] to value |
119 |
| - *@param {number}index |
120 |
| - *@param {number} value |
| 152 | + *Left child index. |
| 153 | + *@param {number}parentIndex |
| 154 | + *@return {number} |
121 | 155 | */
|
122 |
| -update(index,value){ |
123 |
| -this.array[index]=value; |
124 |
| -this.updateRec(1,index,value,0,this.n-1); |
| 156 | +getLeftChildIndex(parentIndex){ |
| 157 | +return(2*parentIndex)+1; |
125 | 158 | }
|
126 | 159 |
|
127 | 160 | /**
|
128 |
| - *@param {number} root |
129 |
| - *@param {number} index |
130 |
| - *@param {number} value |
131 |
| - *@param {number} l |
132 |
| - *@param {number} r |
| 161 | + * Right child index. |
| 162 | + *@param {number} parentIndex |
| 163 | + *@return {number} |
133 | 164 | */
|
134 |
| -updateRec(root,index,value,l,r){ |
135 |
| -if(l===r){ |
136 |
| -// we are at tree node containing array[index] |
137 |
| -this.tree[root]=value; |
138 |
| -}else{ |
139 |
| -constmid=Math.floor((l+r)/2); |
140 |
| -// update whichever child index is in, update this.tree[root] |
141 |
| -if(index<=mid){ |
142 |
| -this.updateRec(this.left(root),index,value,l,mid); |
143 |
| -}else{ |
144 |
| -this.updateRec(this.right(root),index,value,mid+1,r); |
145 |
| -} |
146 |
| -this.tree[root]=this.operation(this.tree[this.left(root)],this.tree[this.right(root)]); |
147 |
| -} |
| 165 | +getRightChildIndex(parentIndex){ |
| 166 | +return(2*parentIndex)+2; |
148 | 167 | }
|
149 | 168 | }
|