703131. Average of Prefix
Easy
Average of Prefix
Summary
Given an array of integers, calculate the average of all prefixes (subarrays ending at each index). This problem involves arrays and mathematical concepts.
Detailed Explanation
To solve this problem, we can use a prefix sum approach. A prefix sum is the cumulative sum of elements up to a certain point in the array. We'll keep track of the running sum as we iterate through the array, and then calculate the average by dividing the current sum by the index plus one.
Here's the step-by-step breakdown:
- Initialize an empty array
prefixSumsto store the prefix sums. - Iterate through the input array
arr. For each element at indexi, add the current element to the running sum and append it toprefixSums. - To calculate the average of a prefix, simply divide the corresponding prefix sum by
(i + 1). - Return the calculated averages as an array.
Here's an ASCII art diagram illustrating the process:
arr = [1, 2, 3, 4, 5]
prefixSums = []
runningSum = 0
for i in range(len(arr)):
runningSum += arr[i]
prefixSums.append(runningSum)
averages = []
for i in range(len(prefixSums)):
averages.append(prefixSums[i] / (i + 1))
print(averages) # Output: [1.0, 1.5, 2.0, 2.5, 3.0]
The time complexity of this solution is O(n), where n is the length of the input array. The space complexity is also O(n) due to the prefixSums array.
Optimized Solutions
Java
public double[] averageOfPrefix(int[] arr) {
int n = arr.length;
double[] prefixSums = new double[n + 1];
double runningSum = 0;
for (int i = 0; i < n; i++) {
runningSum += arr[i];
prefixSums[i + 1] = runningSum;
}
double[] averages = new double[n];
for (int i = 0; i < n; i++) {
averages[i] = prefixSums[i + 1] / (i + 1);
}
return averages;
}