Average Of All Subarrays Given an array, find the average of all subarrays of ‘K’ contiguous elements in it. Let’s understand this problem with real input: Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5 Here is the final output containing the averages of all subarrays of size '5': Output: [2.2, 2.8, 2.4, 3.6, 2.8] Solution def findAverage ( nums , k ): windowSum = sum ( nums [: k ]) #initilize a window of size k average = windowSum / k #initialize average for first window result =[ average ] for i in range ( len ( nums )- k ): #Loop through the array with less k size windowSum = windowSum - nums [ i ]+ nums [ i + k ] # subtract last item of previous window and add next item average = windowSum / k result . append ( average ) return result
Quick Reference for System Design, Architecture and Cloud Engineering Interviews