class GFG {
constructor(arr) {
this
.arr = arr;
this
.n = arr.length;
this
.table = Array.from({ length:
this
.n },
() => Array(Math.ceil(Math.log2(
this
.n)) + 1).fill(0));
this
.buildSparseTable(arr);
}
buildSparseTable(arr) {
for
(let i = 0; i <
this
.n; i++) {
this
.table[i][0] = arr[i];
}
for
(let j = 1; (1 << j) <=
this
.n; j++) {
for
(let i = 0; i + (1 << j) - 1 <
this
.n; i++) {
this
.table[i][j] =
this
.table[i][j - 1]
+
this
.table[i + (1 << (j - 1))][j - 1];
}
}
}
queryNaive(left, right) {
let result = 0;
for
(let i = left; i <= right; i++) {
result +=
this
.arr[i];
}
return
result;
}
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const sparseTable =
new
GFG(arr);
const sumNaive = sparseTable.queryNaive(2, 5);
console.log(
"Sum using Naive approach:"
, sumNaive);