#3427

Sum of Variable Length Subarrays

Easy
ArrayPrefix SumPrefix SumArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a prefix sum array to efficiently calculate the sum of subarrays without repeatedly summing elements. This reduces the time complexity significantly.

⚙️

Algorithm

7 steps
  1. 1Step 1: Create a prefix sum array where prefix[i] is the sum of elements from nums[0] to nums[i].
  2. 2Step 2: Initialize total_sum to 0.
  3. 3Step 3: Loop through each index i from 0 to n-1.
  4. 4Step 4: Determine the starting point start = max(0, i - nums[i]).
  5. 5Step 5: Calculate the subarray sum using the prefix sum array: sum = prefix[i] - (start > 0 ? prefix[start - 1] : 0).
  6. 6Step 6: Add the calculated sum to total_sum.
  7. 7Step 7: Return total_sum after processing all indices.
solution.py11 lines
1def sum_of_variable_length_subarrays(nums):
2    n = len(nums)
3    prefix = [0] * n
4    prefix[0] = nums[0]
5    for i in range(1, n):
6        prefix[i] = prefix[i - 1] + nums[i]
7    total_sum = 0
8    for i in range(n):
9        start = max(0, i - nums[i])
10        total_sum += prefix[i] - (prefix[start - 1] if start > 0 else 0)
11    return total_sum

Complexity note: The time complexity is O(n) because we only loop through the array a constant number of times. The space complexity is O(n) due to the prefix sum array.

  • 1Understanding how to calculate subarray sums efficiently is crucial.
  • 2Prefix sums can significantly reduce the time complexity of problems involving cumulative sums.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.