# Sum of all subarrays of size K

Given an array arr[] and an integer K, the task is to calculate the sum of all subarrays of size K.

Examples:

Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 3
Output: 6 9 12 15
Explanation:
All subarrays of size k and their sum:
Subarray 1: {1, 2, 3} = 1 + 2 + 3 = 6
Subarray 2: {2, 3, 4} = 2 + 3 + 4 = 9
Subarray 3: {1, 2, 3} = 3 + 4 + 5 = 12
Subarray 4: {1, 2, 3} = 4 + 5 + 6 = 15

Input: arr[] = {1, -2, 3, -4, 5, 6}, K = 2
Output: -1, 1, -1, 1, 11
Explanation:
All subarrays of size K and their sum:
Subarray 1: {1, -2} = 1 – 2 = -1
Subarray 2: {-2, 3} = -2 + 3 = -1
Subarray 3: {3, 4} = 3 – 4 = -1
Subarray 4: {-4, 5} = -4 + 5 = 1
Subarray 5: {5, 6} = 5 + 6 = 11

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: The naive approach will be to generate all subarrays of size K and find the sum of each subarray using iteration.

Below is the implementation of the above approach:

## C/C++

 `// C++ implementaion to find the sum ` `// of all subarrays of size K ` ` `  `#include ` `using` `namespace` `std; ` ` `  `// Function to find the sum of  ` `// all subarrays of size K ` `int` `calcSum(``int` `arr[], ``int` `n, ``int` `k) ` `{ ` ` `  `    ``// Loop to consider every  ` `    ``// subarray of size K ` `    ``for` `(``int` `i = 0; i <= n - k; i++) { ` `         `  `        ``// Initialize sum = 0 ` `        ``int` `sum = 0; ` ` `  `        ``// Calculate sum of all elements ` `        ``// of current subarray ` `        ``for` `(``int` `j = i; j < k + i; j++) ` `            ``sum += arr[j]; ` ` `  `        ``// Print sum of each subarray ` `        ``cout << sum << ``" "``; ` `    ``} ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` `    ``int` `arr[] = { 1, 2, 3, 4, 5, 6 }; ` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr); ` `    ``int` `k = 3; ` ` `  `    ``// Function Call ` `    ``calcSum(arr, n, k); ` ` `  `    ``return` `0; ` `} `

## Java

 `// Java implementaion to find the sum ` `// of all subarrays of size K ` `class` `GFG{ ` `  `  `// Function to find the sum of  ` `// all subarrays of size K ` `static` `void` `calcSum(``int` `arr[], ``int` `n, ``int` `k) ` `{ ` `  `  `    ``// Loop to consider every  ` `    ``// subarray of size K ` `    ``for` `(``int` `i = ``0``; i <= n - k; i++) { ` `          `  `        ``// Initialize sum = 0 ` `        ``int` `sum = ``0``; ` `  `  `        ``// Calculate sum of all elements ` `        ``// of current subarray ` `        ``for` `(``int` `j = i; j < k + i; j++) ` `            ``sum += arr[j]; ` `  `  `        ``// Print sum of each subarray ` `        ``System.out.print(sum+ ``" "``); ` `    ``} ` `} ` `  `  `// Driver Code ` `public` `static` `void` `main(String[] args) ` `{ ` `    ``int` `arr[] = { ``1``, ``2``, ``3``, ``4``, ``5``, ``6` `}; ` `    ``int` `n = arr.length; ` `    ``int` `k = ``3``; ` `  `  `    ``// Function Call ` `    ``calcSum(arr, n, k);  ` `} ` `} ` ` `  `// This code is contributed by Rajput-Ji `

## C#

 `// C# implementaion to find the sum ` `// of all subarrays of size K ` `using` `System;  ` ` `  `class` `GFG   ` `{  ` `   `  `    ``// Function to find the sum of  ` `    ``// all subarrays of size K ` `    ``static`  `void` `calcSum(``int``[] arr, ``int` `n, ``int` `k) ` `    ``{ ` `     `  `        ``// Loop to consider every  ` `        ``// subarray of size K ` `        ``for` `(``int` `i = 0; i <= n - k; i++) { ` `             `  `            ``// Initialize sum = 0 ` `            ``int` `sum = 0; ` `     `  `            ``// Calculate sum of all elements ` `            ``// of current subarray ` `            ``for` `(``int` `j = i; j < k + i; j++) ` `                ``sum += arr[j]; ` `     `  `            ``// Print sum of each subarray ` `            ``Console.Write(sum + ``" "``); ` `        ``} ` `    ``} ` `     `  `    ``// Driver Code ` `    ``static` `void` `Main()  ` `    ``{ ` `        ``int``[] arr = ``new` `int``[] { 1, 2, 3, 4, 5, 6 }; ` `        ``int` `n = arr.Length; ` `        ``int` `k = 3; ` `     `  `        ``// Function Call ` `        ``calcSum(arr, n, k); ` `     `  `    ``} ` `} ` ` `  `// This code is contributed by shubhamsingh10 `

## Python3

 `# Python3 implementaion to find the sum ` `# of all subarrays of size K ` `  `  `# Function to find the sum of  ` `# all subarrays of size K ` `def` `calcSum(arr, n, k): ` `  `  `    ``# Loop to consider every  ` `    ``# subarray of size K ` `    ``for` `i ``in` `range``(n ``-` `k ``+` `1``): ` `          `  `        ``# Initialize sum = 0 ` `        ``sum` `=` `0` `  `  `        ``# Calculate sum of all elements ` `        ``# of current subarray ` `        ``for` `j ``in` `range``(i, k ``+` `i): ` `            ``sum` `+``=` `arr[j] ` `  `  `        ``# Prsum of each subarray ` `        ``print``(``sum``, end``=``" "``) ` `  `  `# Driver Code ` `arr``=``[``1``, ``2``, ``3``, ``4``, ``5``, ``6``] ` `n ``=` `len``(arr) ` `k ``=` `3` ` `  `# Function Call ` `calcSum(arr, n, k) ` ` `  `# This code is contributed by mohit kumar 29 `

Output:

```6 9 12 15
```

Performance Analysis:

• Time Complexity: As in the above approach, There are two loops, where first loop runs (N – K) times and second loop runs for K times. Hence the Time Complexity will be O(N*K).
• Auxiliary Space Complexity: As in the above approach, There is no extra space used. Hence the auxiliary space complexity will be O(1).

Efficient Approach: Using Sliding Window The idea is to use the sliding window approach to find the sum of all possible subarrays in the array.

• For each size in the range [0, K], find the sum of the first window of size K and store it in an array.
• Then for each size in the range [K, N], add the next element which contributes into the sliding window and subtract the element which pops out from the window.
```// Adding the element which
// adds into the new window
sum = sum + arr[j]

// Subtracting the element which
// pops out from the window
sum = sum - arr[j-k]

where sum is the variable to store the result
arr is the given array
j is the loop variable in range [K, N]
```

Below is the implementation of the above approach:

## C/C++

 `// C++ implementaion to find the sum ` `// of all subarrays of size K ` ` `  `#include ` `using` `namespace` `std; ` ` `  `// Function to find the sum of  ` `// all subarrays of size K ` `int` `calcSum(``int` `arr[], ``int` `n, ``int` `k) ` `{ ` `    ``// Initialize sum = 0 ` `    ``int` `sum = 0; ` ` `  `    ``// Consider first subarray of size k ` `    ``// Store the sum of elements ` `    ``for` `(``int` `i = 0; i < k; i++) ` `        ``sum += arr[i]; ` ` `  `    ``// Print the current sum ` `    ``cout << sum << ``" "``; ` ` `  `    ``// Consider every subarray of size k ` `    ``// Remove first element and add current ` `    ``// element to the window ` `    ``for` `(``int` `i = k; i < n; i++) { ` `         `  `        ``// Add the element which enters ` `        ``// into the window and substract ` `        ``// the element which pops out from ` `        ``// the window of the size K ` `        ``sum = (sum - arr[i - k]) + arr[i]; ` `         `  `        ``// Print the sum of subarray ` `        ``cout << sum << ``" "``; ` `    ``} ` `} ` ` `  `// Drivers Code ` `int` `main() ` `{ ` `    ``int` `arr[] = { 1, 2, 3, 4, 5, 6 }; ` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr); ` `    ``int` `k = 3; ` `     `  `    ``// Function Call ` `    ``calcSum(arr, n, k); ` ` `  `    ``return` `0; ` `} `

## Java

 `// Java implementaion to find the sum ` `// of all subarrays of size K ` `class` `GFG{ ` ` `  `// Function to find the sum of  ` `// all subarrays of size K ` `static` `void` `calcSum(``int` `arr[], ``int` `n, ``int` `k) ` `{ ` `    ``// Initialize sum = 0 ` `    ``int` `sum = ``0``; ` ` `  `    ``// Consider first subarray of size k ` `    ``// Store the sum of elements ` `    ``for` `(``int` `i = ``0``; i < k; i++) ` `        ``sum += arr[i]; ` ` `  `    ``// Print the current sum ` `    ``System.out.print(sum+ ``" "``); ` ` `  `    ``// Consider every subarray of size k ` `    ``// Remove first element and add current ` `    ``// element to the window ` `    ``for` `(``int` `i = k; i < n; i++) { ` `         `  `        ``// Add the element which enters ` `        ``// into the window and substract ` `        ``// the element which pops out from ` `        ``// the window of the size K ` `        ``sum = (sum - arr[i - k]) + arr[i]; ` `         `  `        ``// Print the sum of subarray ` `        ``System.out.print(sum+ ``" "``); ` `    ``} ` `} ` ` `  `// Drivers Code ` `public` `static` `void` `main(String[] args) ` `{ ` `    ``int` `arr[] = { ``1``, ``2``, ``3``, ``4``, ``5``, ``6` `}; ` `    ``int` `n = arr.length; ` `    ``int` `k = ``3``; ` `     `  `    ``// Function Call ` `    ``calcSum(arr, n, k); ` `} ` `} ` ` `  `// This code is contributed by sapnasingh4991 `

## Python3

 `# Python3 implementaion to find the sum ` `# of all subarrays of size K ` `  `  `# Function to find the sum of  ` `# all subarrays of size K ` `def` `calcSum(arr,  n, k): ` ` `  `    ``# Initialize sum = 0 ` `    ``sum` `=` `0` `  `  `    ``# Consider first subarray of size k ` `    ``# Store the sum of elements ` `    ``for` `i ``in` `range``( k): ` `        ``sum` `+``=` `arr[i] ` `  `  `    ``# Print the current sum ` `    ``print``( ``sum` `,end``=` `" "``) ` `  `  `    ``# Consider every subarray of size k ` `    ``# Remove first element and add current ` `    ``# element to the window ` `    ``for` `i ``in` `range``(k,n): ` `          `  `        ``# Add the element which enters ` `        ``# into the window and substract ` `        ``# the element which pops out from ` `        ``# the window of the size K ` `        ``sum` `=` `(``sum` `-` `arr[i ``-` `k]) ``+` `arr[i] ` `          `  `        ``# Print the sum of subarray ` `        ``print``( ``sum` `,end``=``" "``) ` `  `  `# Drivers Code ` `if` `__name__ ``=``=` `"__main__"``: ` ` `  `    ``arr ``=` `[ ``1``, ``2``, ``3``, ``4``, ``5``, ``6` `] ` `    ``n ``=` `len``(arr) ` `    ``k ``=` `3` `      `  `    ``# Function Call ` `    ``calcSum(arr, n, k) ` `  `  `# This code is contributed by chitranayal `

## C#

 `// C# implementaion to find the sum ` `// of all subarrays of size K ` `using` `System; ` ` `  `class` `GFG{ ` `  `  `// Function to find the sum of  ` `// all subarrays of size K ` `static` `void` `calcSum(``int` `[]arr, ``int` `n, ``int` `k) ` `{ ` `    ``// Initialize sum = 0 ` `    ``int` `sum = 0; ` `  `  `    ``// Consider first subarray of size k ` `    ``// Store the sum of elements ` `    ``for` `(``int` `i = 0; i < k; i++) ` `        ``sum += arr[i]; ` `  `  `    ``// Print the current sum ` `    ``Console.Write(sum+ ``" "``); ` `  `  `    ``// Consider every subarray of size k ` `    ``// Remove first element and add current ` `    ``// element to the window ` `    ``for` `(``int` `i = k; i < n; i++) { ` `          `  `        ``// Add the element which enters ` `        ``// into the window and substract ` `        ``// the element which pops out from ` `        ``// the window of the size K ` `        ``sum = (sum - arr[i - k]) + arr[i]; ` `          `  `        ``// Print the sum of subarray ` `        ``Console.Write(sum + ``" "``); ` `    ``} ` `} ` `  `  `// Drivers Code ` `public` `static` `void` `Main(String[] args) ` `{ ` `    ``int` `[]arr = { 1, 2, 3, 4, 5, 6 }; ` `    ``int` `n = arr.Length; ` `    ``int` `k = 3; ` `      `  `    ``// Function Call ` `    ``calcSum(arr, n, k); ` `} ` `} ` ` `  `// This code is contributed by 29AjayKumar `

Output:

```6 9 12 15
```

Performance Analysis:

• Time Complexity: As in the above approach, There is one loop which take O(N) time. Hence the Time Complexity will be O(N).
• Auxiliary Space Complexity: As in the above approach, There is no extra space used. Hence the auxiliary space complexity will be O(1).

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

6

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.