Range sum query using Sparse Table in JavaScript Array Last Updated : 20 Nov, 2023 Comments Improve Suggest changes Like Article Like Report In this article we will learn about Range sum query using Sparse Table in JavaScript Array, The Sparse Table is a data structure that efficiently solves static range query problems. In the context of the range sum queries, Sparse Table precomputes and stores the sum of the ranges of elements in an array. This allows for fast retrieval of the sum of any range within the array. These are the following approaches by using these we can Range sum query using a Sparse Table in JavaScript Array: Table of Content Precompute and Query (Naive)Precompute and Query with Optimized LoopPrecompute and Query (Naive)In the naive approach of implementing a Sparse Table for the range sum queries. We follow a straightforward process of precomputing the table and querying the sum for the given range.Example: In this example, we are implementing the above-explained approach. JavaScript 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) { // Initialize table with the array elements for (let i = 0; i < this.n; i++) { this.table[i][0] = arr[i]; } // Build sparse table using the dynamic programming 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; // Naively sum elements in the range for (let i = left; i <= right; i++) { result += this.arr[i]; } return result; } } // Example Usage const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const sparseTable = new GFG(arr); // Query using Naive approach const sumNaive = sparseTable.queryNaive(2, 5); console.log("Sum using Naive approach:", sumNaive); OutputSum using Naive approach: 18 Precompute and Query with Optimized LoopIn this approach, we optimize the loop within query method to achieve the faster range sum queries. The optimization involves iterating through the sparse table in a more efficient way.Reducing the time complexity of range sum queries.Example: In this example, we are implementing the above-explained approach. JavaScript class GFG { constructor(arr) { this.table = this.buildSparseTable(arr); } // Build Sparse Table buildSparseTable(arr) { const n = arr.length; const table = new Array(n).fill() .map(() => new Array(Math.ceil(Math.log2(n)) + 1).fill(0)); // Fill the first column with the array values for (let i = 0; i < n; i++) { table[i][0] = arr[i]; } // Build the sparse table using the dynamic programming for (let j = 1; (1 << j) <= n; j++) { for (let i = 0; i + (1 << j) <= n; i++) { // Compute the minimum value in current range table[i][j] = table[i][j - 1] + table[i + (1 << (j - 1))][j - 1]; } } return table; } // Optimized Query method queryOptimized(left, right) { let result = 0; // Iterate through powers of 2 in descending order for (let j = Math.floor(Math.log2(right - left + 1)); j >= 0; j--) { // Check if the current power of 2 is within the range if ((1 << j) <= right - left + 1) { // Update the result and move to // next non-overlapping range result += this.table[left][j]; left += 1 << j; } } return result; } } // Example Usage const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const sparseTable = new GFG(arr); // Query using Optimized approach const sumOptimized = sparseTable.queryOptimized(0, 0); console.log("Sum using Optimized approach:", sumOptimized); OutputSum using Optimized approach: 1 Comment More infoAdvertise with us Next Article Range sum query using Sparse Table in JavaScript Array M mguru4c05q Follow Improve Article Tags : JavaScript Web Technologies Geeks Premier League javascript-array JavaScript-DSA Geeks Premier League 2023 +2 More Similar Reads How to filter Nested Array using Key in JavaScript ? Filtering a nested array in JavaScript involves the process of selectively extracting elements from an array of objects, where each object contains another array. We will discuss how can we filter Nested Array using the key in JavaScript. Filtering a nested array based on a key in JavaScript can be 3 min read Javascript Program for Mean of range in array Given an array of n integers. You are given q queries. Write a program to print the floor value of mean in range l to r for each query in a new line.Examples : Input : arr[] = {1, 2, 3, 4, 5} q = 3 0 2 1 3 0 4 Output : 2 3 3 Here for 0 to 2 (1 + 2 + 3) / 3 = 2 Input : arr[] = {6, 7, 8, 10} q = 2 0 3 3 min read Split JavaScript Array in Chunks Using Lodash? When working with arrays in JavaScript, you may encounter situations where you need to split an array into smaller chunks. This can be particularly useful when dealing with large datasets or when performing operations in a more manageable and efficient manner. The Lodash library provides a convenien 2 min read Find Mode of an Array using JavaScript To find the mode in an array with JavaScript, where the mode is the number occurring most frequently. Various approaches can be employed to find the mode, and an array may have multiple modes if multiple numbers occur with the same highest frequency. Example:Input:3, 6, 4, 6, 3, 6, 6, 7 , 6, 3 , 3Ou 4 min read How to load data from JavaScript array using jQuery DataTables plugin ? DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for our webpages. It is a simple-to-use plug-in with a huge range of options for the developer's custom changes. The common features of the DataTable plugin are paging, multiple column ordering, sorting 2 min read Print all Negative numbers in a Range in JavaScript Array To print all the negative numbers in a range from the JavaScript array, we need to iterate over the array and apply the condition to filter out the negative numbers. Once the elements are extracted, we can print them in the console. Example:Input: arr = [-22, 45, 63, -88, -69]Range: [-1 to -70]Outpu 3 min read How to convert JSON data to a html table using JavaScript/jQuery ? To convert JSON data into an HTML table, there are multiple approaches, each of which has its own strengths. Let's walk through both approaches you mentioned, detailing how each one works.Table of ContentUsing for loopUsing JSON.stringify() MethodApproach 1: Using for loopTake the JSON Object in a v 4 min read Dense and Sparse Array in JavaScript In JavaScript, an array is a data structure used for storing a collection of values. Each value in the collection is assigned a unique index number. Arrays in JavaScript can contain values of any data type, such as strings, numbers, objects, and even other arrays. In JavaScript, arrays can be of two 7 min read JavaScript RangeError - Invalid array length This JavaScript exception Invalid array length occurs when creating an Array or an ArrayBuffer of the array length either negative or greater than or equal to 232. It can also occur if the length property is set manually to a value either negative or greater than or equal to 232. Output message: Ran 2 min read How to traverse 2D arrays in JavaScript? A two-dimensional array or simply 2D array is a format to store data in a grid format that is rows and columns format. There is no special way of declaring a 2D array in JavaScript, we can simply pass an array as an element inside another array. the array obtained in this method will be created as a 6 min read Like