JavaScript Program to Find the Sum of Elements Between Two Given Indices in an Array
Last Updated :
17 Jun, 2024
In JavaScript programming, there are often scenarios where we need to calculate the sum of elements within a specific range in an array. This can be useful in various applications, such as calculating subarray sums in algorithms or performing range-based calculations in data analysis.
Example:
Input: const array = [1, 2, 3, 4, 5];
const startIndex = 1;
const endIndex = 3;
Output: 9
Naive Approach
The most straightforward approach is to iterate through the array elements within the given range and calculate their sum.
Example: Implementation to Find the sum of elements between two given indices in an array using a naive approach.
JavaScript
function sum(array, start, end) {
let sum = 0;
for (let i = start; i <= end; i++) {
sum += array[i];
}
return sum;
}
const array = [1, 2, 3, 4, 5];
const startIndex = 1;
const endIndex = 3;
console.log("Sum between indices:",
sum(array, startIndex, endIndex));
OutputSum between indices: 9
Time Complexity: O(n), where n is the number of elements between startIndex and endIndex.
Space Complexity: O(1), constant space used.
Using Prefix Sum Technique
This approach involves precomputing prefix sums for the array. We can create an auxiliary array where each element represents the sum of elements from the beginning of the array up to that index. Then, we can calculate the sum between two indices by subtracting the prefix sum at the start index from the prefix sum at the end index + 1.
Example: Implementation to Find the sum of elements between two given indices in an array using Prefix Sum Technique.
JavaScript
function sum(arr, start, end) {
let prefixSum = [0];
for (let i = 0; i < arr.length; i++) {
prefixSum[i + 1] = prefixSum[i] + arr[i];
}
return prefixSum[end + 1] - prefixSum[start];
}
const array = [1, 3, 5, 7, 9, 11];
const startIndex = 2;
const endIndex = 4;
console.log(sum(array, startIndex, endIndex));
Time Complexity: O(n), where n is the number of elements between startIndex and endIndex.
Space Complexity: O(1), constant space used.
Using reduce Method
This approach uses the reduce method to accumulate the sum of the elements between the specified indices.
Example: Implementation to Find the sum of elements between two given indices in an array using a reduce Method.
JavaScript
function sumBetweenIndices(arr, start, end) {
return arr.slice(start, end + 1).reduce((acc, curr) => acc + curr, 0);
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const start = 2;
const end = 5;
const result = sumBetweenIndices(arr, start, end);
console.log(result);
Time Complexity: O(n), where n is the number of elements between startIndex and endIndex.
Space Complexity: O(1).
Similar Reads
JavaScript Program to Find the Distance Value between Two Arrays We will be given two integer arrays and an integer d. The task is to calculate the distance between the two given arrays based on the given integer value. The distance value will be calculated as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <=
3 min read
JavaScript Program to Construct an Array from its pair-sum Array The pair-sum array is a unique construction that holds the sum of all potential pairs of elements from the original array. At first glance, it might appear to be challenging, but in this article, we'll Construct an array from its pair-sum array and discover some of its most intriguing uses. What is
4 min read
Javascript Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided ar
5 min read
Javascript Program for Range sum queries for anticlockwise rotations of Array by K indices Given an array arr consisting of N elements and Q queries of the following two types: 1 K: For this type of query, the array needs to be rotated by K indices anticlockwise from its current state.2 L R: For this query, the sum of the array elements present in the indices [L, R] needs to be calculated
4 min read
Calculate the Sum and Average of Elements in an ArrayList in Java A Dynamic and Adaptable method for storing and managing collections of elements is to use ArrayList. Finding the total and average of an ArrayList's items is frequently required when working with numerical data that is stored in the list. In this article, we will see how we can sum and find the aver
3 min read
Javascript Program to Find the subarray with least average Given an array arr[] of size n and integer k such that k <= n.Examples : Input: arr[] = {3, 7, 90, 20, 10, 50, 40}, k = 3Output: Subarray between indexes 3 and 5The subarray {20, 10, 50} has the least average among all subarrays of size 3.Input: arr[] = {3, 7, 5, 20, -10, 0, 12}, k = 2Output: Sub
3 min read