Problem
Given an array write an algorithm to find the sum of all the possible sub arrays.
Examples
Example 1:
| |
Solution
Method 1 - By generating all sub arrays
As discussed in Print all sub arrays, find out all the sub arrays and then calculate the sum. Here is the approach:
- Iterate through each starting point of subarrays.
- For each starting point, iterate through each ending point of subarrays.
- Calculate the sum of the subarray from the starting point to the ending point, and accumulate the sum.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n^3), because for each possible subarray, we spend time to sum its elements. There aren(n+1)/2subarrays and summing an individual subarray can takeO(n)time in the worst case. - 🧺 Space complexity:
O(1), as no additional space is required apart from a few variables.
Method 2 - Using prefix sum
- Calculate the prefix sum array, where each element at index
icontains the sum of the array from the start up to indexi. - Iterate through each starting point of subarrays.
- For each subarray starting point, using the prefix sum array calculate the sum for each ending point.
- Accumulate the subarray sums.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n^2)for iterating through the subarrays plusO(n)for computing the prefix sum, thusO(n^2). - 🧺 Space complexity:
O(n)due to the prefix sum array.
Method 3 - Counting number of occurrences of numbers in subarray
Consider the array [1, 2, 3, 4]. The subarrays are:
| |
For each element, the number of occurrences can be observed as follows:
- 1 appears 4 times
- 2 appears 6 times
- 3 appears 6 times
- 4 appears 4 times
By examining the subarrays starting with each element, we observe:
- For 1, subarrays are
[1], [1 2], [1 2 3], [1 2 3 4] - For 2, subarrays are
[2], [2 3], [2 3 4] - For 3, subarrays are
[3], [3 4] - For 4, subarrays are
[4]
Thus, the number of times each element appears at the first position will be equal to n (in this case, n = 4). The next element, 2, will appear n - 1 times, and so on. Hence, the ith element appears (n-i) times.
Occurrences at the first positions:
- 1 appears 4 times.
- 2 appears 3 times.
- 3 appears 2 times.
- 4 appears 1 time.
Subtracting these from the initial count gives us:
- 1: 0 remaining
- 2: 3 remaining
- 3: 4 remaining
- 4: 3 remaining
The formula (n-i) * i helps us determine this pattern.
So, the total number of occurrences for the ith element is (n-i) * i + (n-i) which simplifies to (n-i) * (i + 1).
For the array [1, 2, 3, 4], the total sum is:
1 * (4-0) * (0+1) + 2 * (4-1) * (1+1) + 3 * (4-2) * (2+1) + 4 * (4-3) * (3+1)- This equals
1 * 4 + 2 * 6 + 3 * 6 + 4 * 4 = 50.
For the array [1, 2, 3], the total sum is:
1 * (3-0) * (0+1) + 2 * (3-1) * (1+1) + 3 * (3-2) * (2+1)- This equals
1 * 3 + 2 * 4 + 3 * 3 = 3 + 8 + 9 = 20.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)