Sponsored
Sponsored
The brute force approach involves calculating the sum of all possible subarrays in the given array. Once all subarray sums are computed, we can sort this list of sums. Finally, sum the elements from the sorted list between the given 'left' and 'right' indices, returning the result modulo 10^9 + 7. This approach is straightforward to implement but not necessarily optimal in terms of time complexity.
Time Complexity: O(n^2 log n) due to calculating O(n^2) subarray sums and sorting them.
Space Complexity: O(n^2), for storing subarray sums.
1function rangeSum(nums, n, left, right) {
2 const MOD = 1e9 + 7;
3 let subarraySums = [];
4
5 for (let i = 0; i < n; i++) {
6 let sum = 0;
7 for (let j = i; j < n; j++) {
8 sum += nums[j];
9 subarraySums.push(sum);
10 }
11 }
12
13 subarraySums.sort((a, b) => a - b);
14
15 let result = 0;
16 for (let i = left - 1; i < right; i++) {
17 result = (result + subarraySums[i]) % MOD;
18 }
19
20 return result;
21}
22
23// Example usage:
24const nums = [1, 2, 3, 4];
25console.log(rangeSum(nums, 4, 1, 5));
In JavaScript, arrays are used to store all possible subarray sums, which are then sorted numerically. Similar to other implementations, the range is traversed to compute the required sum, applying modulo arithmetic to manage large values.
This approach leverages a min-heap (priority queue) data structure to efficiently find the range of the smallest elements. By pushing subarray sums into the min-heap and ensuring its size does not exceed 'right', we can directly extract the required sum by polling from the min-heap. This method avoids complete sorting and is more efficient than direct sorting for larger input sizes.
Time Complexity: O(n^2 log M), where M is the maximum heap size (i.e., 'right').
Space Complexity: O(M), since we maintain only 'M' elements in the heap.
This C implementation uses a simulated min-heap by employing a binary heap data structure in an array. Subarray sums are pushed onto the heap if the heap size has not yet reached 'right', or if a sum is smaller than the maximum element on the heap, enhancing efficiency by only keeping relevant elements for subsequent calculation.