Average of All Subarrays of Size K

Problem

Return the average of every contiguous subarray of size k.

Input:  nums = [1,3,2,6,-1,4,1,8,2], k = 5
Output: [2.2, 2.8, 2.4, 3.6, 2.8]

Python Solution

def average_of_subarrays(nums, k):
    result = []
    window_sum = sum(nums[:k])
    result.append(window_sum / k)
    for i in range(k, len(nums)):
        window_sum += nums[i] - nums[i - k]
        result.append(window_sum / k)
    return result

C++ Solution

vector<double> averageOfSubarrays(vector<int>& nums, int k) {
    vector<double> result;
    double windowSum = 0;
    for (int i = 0; i < k; i++) windowSum += nums[i];
    result.push_back(windowSum / k);
    for (int i = k; i < nums.size(); i++) {
        windowSum += nums[i] - nums[i - k];
        result.push_back(windowSum / k);
    }
    return result;
}

Java Solution

class Solution {
    public double[] averageOfSubarrays(int[] nums, int k) {
        double[] result = new double[nums.length - k + 1];
        double windowSum = 0;
        for (int i = 0; i < k; i++) windowSum += nums[i];
        result[0] = windowSum / k;
        for (int i = k; i < nums.length; i++) {
            windowSum += nums[i] - nums[i - k];
            result[i - k + 1] = windowSum / k;
        }
        return result;
    }
}

Complexity

Time: O(n) — each element is added once and removed once from the running sum. Space: O(n) for the output array of averages.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.