Range sum query using Sparse Table in JavaScript Array Last Updated : 20 Nov, 2023 Summarize Comments Improve Suggest changes Share 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 M mguru4c05q Follow Improve Article Tags : JavaScript Web Technologies Geeks Premier League javascript-array JavaScript-DSA Geeks Premier League 2023 +2 More Similar Reads Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav 11 min read Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De 5 min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications 15+ min read React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version 7 min read JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q 15+ min read Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact 12 min read 3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power 13 min read Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read Like