Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of all subsets of a given size (=K)
Next article icon

Sum of all subarrays of size K

Last Updated : 11 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: {3, 4, 5} = 3 + 4 + 5 = 12 
Subarray 4: {4, 5, 6} = 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 

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++ implementation to find the sum
// of all subarrays of size K
  
#include <iostream>
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[0]);
    int k = 3;
  
    // Function Call
    calcSum(arr, n, k);
  
    return 0;
}
 
 

Java




// Java implementation 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# implementation 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 implementation 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]
  
        # Print sum 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
 
 

Javascript




<script>
  
// JavaScript implementation to find the sum
// of all subarrays of size K
  
// Function to find the sum of 
// all subarrays of size K
function calcSum(arr, n, k)
{
  
    // Loop to consider every 
    // subarray of size K
    for (var i = 0; i <= n - k; i++) {
          
        // Initialize sum = 0
        var sum = 0;
  
        // Calculate sum of all elements
        // of current subarray
        for (var j = i; j < k + i; j++)
            sum += arr[j];
  
        // Print sum of each subarray
        document.write(sum + " ");
    }
}
  
// Driver Code
var arr = [ 1, 2, 3, 4, 5, 6 ];
var n = arr.length;
var k = 3;
  
// Function Call
calcSum(arr, n, k);
  
  
</script>
 
 
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++ implementation to find the sum
// of all subarrays of size K
  
#include <iostream>
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 subtract
        // 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[0]);
    int k = 3;
      
    // Function Call
    calcSum(arr, n, k);
  
    return 0;
}
 
 

Java




// Java implementation 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 subtract
        // 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 implementation 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 subtract
        # 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# implementation 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 subtract
        // 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
 
 

Javascript




<script>
  
// Javascript implementation to find the sum
// of all subarrays of size K
  
// Function to find the sum of
// all subarrays of size K
function calcSum(arr, n, k)
{
  
    // Initialize sum = 0
    var sum = 0;
  
    // Consider first subarray of size k
    // Store the sum of elements
    for (var i = 0; i < k; i++)
        sum += arr[i];
  
    // Print the current sum
    document.write( sum + " ");
  
    // Consider every subarray of size k
    // Remove first element and add current
    // element to the window
    for (var i = k; i < n; i++) {
          
        // Add the element which enters
        // into the window and subtract
        // the element which pops out from
        // the window of the size K
        sum = (sum - arr[i - k]) + arr[i];
          
        // Print the sum of subarray
        document.write( sum + " ");
    }
}
  
// Drivers Code
var arr = [ 1, 2, 3, 4, 5, 6 ];
var n = arr.length;
var k = 3;
  
// Function Call
calcSum(arr, n, k);
  
// This code is contributed by noob2000.
</script>
 
 
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).
     

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Sum of all subsets of a given size (=K)
author
spp____
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • sliding-window
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Greedy
  • sliding-window

Similar Reads

  • Sum of XOR of all subarrays
    Given an array containing N positive integers, the task is to find the sum of XOR of all sub-arrays of the array. Examples: Input : arr[] = {1, 3, 7, 9, 8, 7} Output : 128 Input : arr[] = {3, 8, 13} Output : 46 Explanation for second test-case: XOR of {3} = 3 XOR of {3, 8} = 11 XOR of {3, 8, 13} = 6
    13 min read
  • Sum of all Subarrays
    Given an integer array arr[], find the sum of all sub-arrays of the given array. Examples: Input: arr[] = [1, 2, 3]Output: 20Explanation: {1} + {2} + {3} + {2 + 3} + {1 + 2} + {1 + 2 + 3} = 20 Input: arr[] = [1, 2, 3, 4]Output: 50 Naive Approach - O(n^2) Time and O(1) SpaceA simple solution is to ge
    6 min read
  • Sum of bitwise OR of all subarrays
    Given an array of positive integers, find the total sum after performing the bit wise OR operation on all the sub arrays of a given array. Examples: Input : 1 2 3 4 5 Output : 71 Input : 6 5 4 3 2 Output : 84 First initialize the two variable sum=0, sum1=0, variable sum will store the total sum and,
    5 min read
  • Sum of all subsets of a given size (=K)
    Given an array arr[] consisting of N integers and a positive integer K, the task is to find the sum of all the subsets of size K. Examples: Input: arr[] = {1, 2, 4, 5}, K = 2Output: 36Explanation:The subsets of size K(= 2) are = {1, 2}, {1, 4}, {1, 5}, {2, 4}, {2, 5}, {4, 5}. Now, the sum of all sub
    7 min read
  • Sum of products of all possible Subarrays
    Given an array arr[] of N positive integers, the task is to find the sum of the product of elements of all the possible subarrays. Examples: Input: arr[] = {1, 2, 3}Output: 20Explanation: Possible Subarrays are: {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}.Products of all the above subarrays are 1, 2, 3
    6 min read
  • Sum of bitwise AND of all subarrays
    Given an array consisting of N positive integers, find the sum of bit-wise and of all possible sub-arrays of the array. Examples: Input : arr[] = {1, 5, 8} Output : 15 Bit-wise AND of {1} = 1 Bit-wise AND of {1, 5} = 1 Bit-wise AND of {1, 5, 8} = 0 Bit-wise AND of {5} = 5 Bit-wise AND of {5, 8} = 0
    8 min read
  • Subarray of size k with given sum
    Given an array arr[], an integer K and a Sum. The task is to check if there exists any subarray with K elements whose sum is equal to the given sum. If any of the subarray with size K has the sum equal to the given sum then print YES otherwise print NO. Examples: Input: arr[] = {1, 4, 2, 10, 2, 3, 1
    10 min read
  • Subarray of size K with prime sum
    Given an array, arr[] of size N and an integer K, the task is to print a subarray of size K whose sum of elements is a prime number. If more than one such subarray exists, then print any one of them. Examples: Input: arr[] = {20, 7, 5, 4, 3, 11, 99, 87, 23, 45}, K = 4Output: 7 5 4 3Explanation: Sum
    9 min read
  • Largest sum subarray of size at least k
    Given an array and an integer k, the task is to find the sum of elements of a subarray containing at least k elements which has the largest sum. Examples: Input : arr[] = {-4, -2, 1, -3}, k = 2Output : -1Explanation : The sub array is {-2, 1}. Input : arr[] = {1, 1, 1, 1, 1, 1} , k = 2Output : 6 Exp
    14 min read
  • Maximum circular subarray sum of size K
    Given an array arr of size N and an integer K, the task is to find the maximum sum subarray of size k among all contiguous sub-array (considering circular subarray also). Examples: Input: arr = {18, 4, 3, 4, 5, 6, 7, 8, 2, 10}, k = 3 Output: max circular sum = 32 start index = 9 end index = 1 Explan
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences