Given an integer array arr[], find the sum of all sub-arrays of the given array.
Examples:
Input: arr[] = [1, 2, 3]
Output: 20
Explanation: {1} + {2} + {3} + {2 + 3} + {1 + 2} + {1 + 2 + 3} = 20
Input: arr[] = [1, 2, 3, 4]
Output: 50
Naive Approach - O(n^2) Time and O(1) Space
A simple solution is to generate all sub-arrays and compute their sum
Follow the below steps to solve the problem:
- Generate all subarrays using nested loops
- Take the sum of all these subarrays
C++
// Simple C++ program to compute sum of
// subarray elements
#include <bits/stdc++.h>
using namespace std;
int subarraySum(vector<int> &arr) {
int n = arr.size();
int result = 0, temp = 0;
// Pick starting point
for (int i = 0; i < n; i++) {
// Pick ending point
temp = 0;
for (int j = i; j < n; j++) {
// sum subarray between current
// starting and ending points
temp += arr[j];
result += temp;
}
}
return result;
}
int main() {
vector<int> arr = {1, 2, 3};
int n = arr.size();
cout << subarraySum(arr);
return 0;
}
Java
// Java program to compute sum of
// subarray elements
public class GfG {
static int subarraySum(int[] arr) {
int n = arr.length;
int result = 0, temp = 0;
// Pick starting point
for (int i = 0; i < n; i++) {
// Pick ending point
temp = 0;
for (int j = i; j < n; j++) {
// Sum subarray between current starting and ending points
temp += arr[j];
result += temp;
}
}
return result;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3};
System.out.println(subarraySum(arr));
}
}
Python
# Python3 program to compute
# sum of subarray elements
def subarraySum(arr):
n = len(arr)
result = 0
# Pick starting point
for i in range(n):
temp = 0
# Pick ending point
for j in range(i, n):
# Sum subarray between current starting and ending points
temp += arr[j]
result += temp
return result
arr = [1, 2, 3]
print(subarraySum(arr))
C#
// C# program to compute sum of
// subarray elements
using System;
class GfG {
static int SubarraySum(int[] arr) {
int n = arr.Length;
int result = 0;
// Pick starting point
for (int i = 0; i < n; i++) {
int temp = 0;
// Pick ending point
for (int j = i; j < n; j++) {
// Sum subarray between current starting and ending points
temp += arr[j];
result += temp;
}
}
return result;
}
static void Main() {
int[] arr = { 1, 2, 3 };
Console.WriteLine(SubarraySum(arr));
}
}
JavaScript
// JavaScript program to compute sum of
// subarray elements
function subarraySum(arr) {
let n = arr.length;
let result = 0;
// Pick starting point
for (let i = 0; i < n; i++) {
let temp = 0;
// Pick ending point
for (let j = i; j < n; j++) {
// Sum subarray between current starting and ending points
temp += arr[j];
result += temp;
}
}
return result;
}
let arr = [1, 2, 3];
console.log(subarraySum(arr));
Expected Approach - O(n) Time and O(1) Space
If we take a close look then we observe a pattern.
Let's take an example:
arr[] = [1, 2, 3], n = 3
All subarrays : [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]
here first element 'arr[0]' appears 3 times
second element 'arr[1]' appears 4 times
third element 'arr[2]' appears 3 times
Every element arr[i] appears in two types of subsets:
i) In subarrays beginning with arr[i]. There are
(n-i) such subsets. For example [2] appears
in [2] and [2, 3].
ii) In (n-i)*i subarrays where this element is not
first element. For example [2] appears in [1, 2] and [1, 2, 3].
Total of above (i) and (ii) = (n-i) + (n-i)*i = (n-i)(i+1)
For arr[] = {1, 2, 3}, sum of subarrays is:
arr[0] * ( 0 + 1 ) * ( 3 - 0 ) +
arr[1] * ( 1 + 1 ) * ( 3 - 1 ) +
arr[2] * ( 2 + 1 ) * ( 3 - 2 )
= 1*3 + 2*4 + 3*3
= 20
Follow the below steps to solve the problem:
- Declare an integer answer equal to zero
- Run a for loop for i [0, n]
- Add arr[i] * (i+1) * (n-i) into the answer at each iteration
- Return answer
C++
// C++ program to compute sum of
// subarray elements
#include <bits/stdc++.h>
using namespace std;
int subarraySum(vector<int>&arr) {
int n=arr.size();
int result = 0;
// computing sum of subarray using formula
for (int i = 0; i < n; i++)
result += (arr[i] * (i + 1) * (n - i));
// return all subarray sum
return result;
}
int main() {
vector<int>arr = { 1, 2, 3 };
int n = arr.size();
cout <<subarraySum(arr);
return 0;
}
Java
// Java program to compute sum of
// subarray elements
class GfG {
static int subarraySum(int[] arr) {
int n = arr.length;
int result = 0;
// Computing sum of subarrays using the formula
for (int i = 0; i < n; i++) {
result += (arr[i] * (i + 1) * (n - i));
}
// Return the sum of all subarrays
return result;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3};
System.out.println(subarraySum(arr));
}
}
Python
# Python3 code to compute
# sum of subarray elements
def subarraySum(arr):
n = len(arr)
result = 0
# Computing sum of subarrays using the formula
for i in range(n):
result += arr[i] * (i + 1) * (n - i)
# Return the sum of all subarrays
return result
arr = [1, 2, 3]
print(subarraySum(arr))
C#
// C# program
// to compute sum of
// subarray elements
using System;
class GfG {
static int subarraySum(int[] arr) {
int n = arr.Length;
int result = 0;
// Computing sum of subarrays using the formula
for (int i = 0; i < n; i++) {
result += arr[i] * (i + 1) * (n - i);
}
// Return the sum of all subarrays
return result;
}
static void Main() {
int[] arr = { 1, 2, 3 };
Console.WriteLine(subarraySum(arr));
}
}
JavaScript
// Function to compute the sum of all subarray elements
function subarraySum(arr) {
const n = arr.length;
let result = 0;
// Computing sum of subarrays using the formula
for (let i = 0; i < n; i++) {
result += arr[i] * (i + 1) * (n - i);
}
// Return the sum of all subarrays
return result;
}
const arr = [1, 2, 3];
console.log(subarraySum(arr));
Similar Reads
Sum of XOR of all subarrays Given an array containing N positive integers, the task is to find the sum of XOR of all sub-arrays of the array. Examples: Input : arr[] = {1, 3, 7, 9, 8, 7} Output : 128 Input : arr[] = {3, 8, 13} Output : 46 Explanation for second test-case: XOR of {3} = 3 XOR of {3, 8} = 11 XOR of {3, 8, 13} = 6
13 min read
Sum of all subarrays of size K Given an array arr[] and an integer K, the task is to calculate the sum of all subarrays of size K. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 3 Output: 6 9 12 15 Explanation: All subarrays of size k and their sum: Subarray 1: {1, 2, 3} = 1 + 2 + 3 = 6 Subarray 2: {2, 3, 4} = 2 + 3 + 4 = 9 Sub
11 min read
Sum of bitwise OR of all subarrays Given an array of positive integers, find the total sum after performing the bit wise OR operation on all the sub arrays of a given array. Examples: Input : 1 2 3 4 5 Output : 71 Input : 6 5 4 3 2 Output : 84 First initialize the two variable sum=0, sum1=0, variable sum will store the total sum and,
5 min read
Sum of bitwise AND of all subarrays Given an array consisting of N positive integers, find the sum of bit-wise and of all possible sub-arrays of the array. Examples: Input : arr[] = {1, 5, 8} Output : 15 Bit-wise AND of {1} = 1 Bit-wise AND of {1, 5} = 1 Bit-wise AND of {1, 5, 8} = 0 Bit-wise AND of {5} = 5 Bit-wise AND of {5, 8} = 0
8 min read
Print all subarrays with 0 sum Given an array arr[] of size n, the task is to print all subarrays in the array which has sum 0.Examples: Input: arr = [6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7]Output:Subarray found from Index 2 to 4Subarray found from Index 2 to 6Subarray found from Index 5 to 6Subarray found from Index 6 to 9Subarra
14 min read