Back to Dashboard

Average of K Subarray

Easy

Problem Statement

Given an array of integers and a number ‘K’, we need to find the average of all contiguous subarrays of size ‘K’.

Examples

Example 1:

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

Approach 1 Sliding Window:

  public double[] findAverages(int K, int[] arr) {
    double[] result = new double[arr.length - K + 1];
    var windowStart = 0;
    var windowSum = 0;
    for (int windowEnd = 0; windowEnd < arr.length; windowEnd ++) {
      windowSum += arr[windowEnd];
      if (windowEnd >= K - 1) {
        System.out.println(windowSum);
        result[windowStart] = (double) windowSum / K;
        windowSum -= arr[windowStart];
        windowStart ++;
      }
    }
    return result;
  }

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

ArraySliding Window

Date

2026-02-12
View Problem Source