3427. Sum of Variable Length Subarrays LeetCode Solution
In this guide, you will get 3427. Sum of Variable Length Subarrays LeetCode Solution with the best time and space complexity. The solution to Sum of Variable Length Subarrays problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Sum of Variable Length Subarrays solution in C++
- Sum of Variable Length Subarrays solution in Java
- Sum of Variable Length Subarrays solution in Python
- Additional Resources

Problem Statement of Sum of Variable Length Subarrays
You are given an integer array nums of size n. For each index i where 0 <= i < n, define a subarray nums[start … i] where start = max(0, i – nums[i]).
Return the total sum of all elements from the subarray defined for each index in the array.
Example 1:
Input: nums = [2,3,1]
Output: 11
Explanation:
i
Subarray
Sum
0
nums[0] = [2]
2
1
nums[0 … 1] = [2, 3]
5
2
nums[1 … 2] = [3, 1]
4
Total Sum
11
The total sum is 11. Hence, 11 is the output.
Example 2:
Input: nums = [3,1,1,2]
Output: 13
Explanation:
i
Subarray
Sum
0
nums[0] = [3]
3
1
nums[0 … 1] = [3, 1]
4
2
nums[1 … 2] = [1, 1]
2
3
nums[1 … 3] = [1, 1, 2]
4
Total Sum
13
The total sum is 13. Hence, 13 is the output.
Constraints:
1 <= n == nums.length <= 100
1 <= nums[i] <= 1000
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
3427. Sum of Variable Length Subarrays LeetCode Solution in C++
class Solution {
public:
int subarraySum(vector<int>& nums) {
const int n = nums.size();
int ans = 0;
vector<int> prefix(n + 1);
partial_sum(nums.begin(), nums.end(), prefix.begin() + 1);
for (int i = 0; i < n; ++i)
ans += prefix[i + 1] - prefix[max(0, i - nums[i])];
return ans;
}
};
/* code provided by PROGIEZ */
3427. Sum of Variable Length Subarrays LeetCode Solution in Java
class Solution {
public int subarraySum(int[] nums) {
final int n = nums.length;
int ans = 0;
int[] prefix = new int[n + 1];
for (int i = 0; i < n; ++i)
prefix[i + 1] = prefix[i] + nums[i];
for (int i = 0; i < n; ++i)
ans += prefix[i + 1] - prefix[Math.max(0, i - nums[i])];
return ans;
}
}
// code provided by PROGIEZ
3427. Sum of Variable Length Subarrays LeetCode Solution in Python
class Solution:
def subarraySum(self, nums: list[int]) -> int:
prefix = list(itertools.accumulate(nums, initial=0))
return sum(prefix[i + 1] - prefix[max(0, i - num)]
for i, num in enumerate((nums)))
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.