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, 0, 20}
        k = 4, sum = 18
Output: YES
Subarray = {4, 2, 10, 2}

Input: arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20}
        k = 3, sum = 6
Output: YES


A simple solution is to use nested loops, where we check every subarray of size k.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to check if any Subarray of size 
// K has a given Sum
#include <iostream>
using namespace std;
  
// Function to check if any Subarray of size K
// has a  given Sum
bool checkSubarraySum(int arr[], int n,
                      int k, int sum)
{
    // Consider all blocks starting with i.
    for (int i = 0; i < n - k + 1; i++) {
  
        int current_sum = 0;
  
        // Consider each subarray of size k
        for (int j = 0; j < k; j++)
            current_sum = current_sum + arr[i + j];
  
        if (current_sum == sum) 
            return true;        
    }
    return false;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
    int k = 4;
    int sum = 18;
  
    int n = sizeof(arr) / sizeof(arr[0]);
  
    if (checkSubarraySum(arr, n, k, sum))
        cout << "YES";
    else
        cout << "NO";
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check
// if any Subarray of size 
// K has a given Sum
class GFG 
{
  
// Function to check if any
// Subarray of size K has 
// a given Sum
static boolean checkSubarraySum(int arr[], int n,
                                int k, int sum)
{
    // Consider all blocks 
    // starting with i.
    for (int i = 0; i < n - k + 1; i++)
    {
  
        int current_sum = 0;
  
        // Consider each 
        // subarray of size k
        for (int j = 0; j < k; j++)
            current_sum = current_sum + 
                          arr[i + j];
  
        if (current_sum == sum) 
            return true;     
    }
    return false;
}
  
// Driver code
public static void main(String args[])
{
    int arr[] = new int[] { 1, 4, 2, 10, 2
                            3, 1, 0, 20 };
    int k = 4;
    int sum = 18;
  
    int n = arr.length;
  
    if (checkSubarraySum(arr, n, k, sum))
        System.out.println("YES");
    else
        System.out.println("NO");
}
}
  
// This code is contributed 
// by Kirti_Mangal

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to check 
# if any Subarray of size 
# K has a given Sum
  
# Function to check if
# any Subarray of size 
# K, has a given Sum
def checkSubarraySum(arr, n, k, sum):
      
    # Consider all blocks
    # starting with i.
    for i in range (n - k + 1): 
  
        current_sum = 0;
  
        # Consider each subarray
        # of size k
        for j in range(k):
            current_sum = (current_sum + 
                            arr[i + j]);
  
        if (current_sum == sum):
            return True;     
    return False;
  
# Driver code
arr = [1, 4, 2, 10, 2,
          3, 1, 0, 20];
k = 4;
sum = 18;
  
n = len(arr);
  
if (checkSubarraySum(arr, n, k, sum)):
    print("YES");
else:
    print("NO");
  
# This code is contributed by mits

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to check if any
// Subarray of size K has a given Sum
using System;
class GFG 
{
  
// Function to check if any Subarray
// of size K has a given Sum
static bool checkSubarraySum(int[] arr, int n,
                             int k, int sum)
{
    // Consider all blocks 
    // starting with i.
    for (int i = 0; i < n - k + 1; i++)
    {
  
        int current_sum = 0;
  
        // Consider each 
        // subarray of size k
        for (int j = 0; j < k; j++)
            current_sum = current_sum + 
                            arr[i + j];
  
        if (current_sum == sum) 
            return true;     
    }
    return false;
}
  
// Driver code
static void Main()
{
    int[] arr = new int[] { 1, 4, 2, 10, 
                            2, 3, 1, 0, 20 };
    int k = 4;
    int sum = 18;
  
    int n = arr.Length;
  
    if (checkSubarraySum(arr, n, k, sum))
        Console.WriteLine("YES");
    else
        Console.WriteLine("NO");
}
}
  
// This code is contributed 
// by mits

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to check 
// if any Subarray of size 
// K has a given Sum
  
// Function to check if
// any Subarray of size 
// K, has a given Sum
function checkSubarraySum($arr, $n
                          $k, $sum)
{
    // Consider all blocks starting with i.
    for ($i = 0; $i < $n - $k + 1; $i++) 
    {
  
        $current_sum = 0;
  
        // Consider each subarray of size k
        for ($j = 0; $j < $k; $j++)
            $current_sum = $current_sum
                           $arr[$i + $j];
  
        if ($current_sum == $sum
            return true;     
    }
    return false;
}
  
// Driver code
$arr = array(1, 4, 2, 10, 2,
             3, 1, 0, 20);
$k = 4;
$sum = 18;
  
$n = sizeof($arr);
  
if (checkSubarraySum($arr, $n
                     $k, $sum))
    echo "YES";
else
    echo "NO";
  
// This code is contributed by mits
?>

chevron_right


Output:

YES

Time Complexity: O(n * k)

An efficient solution is to check sliding window technique and simultaneously check if the sum is equal to the given sum.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to check if any Subarray of size 
// K has a given Sum
#include <iostream>
using namespace std;
  
// Function to check if any Subarray of size K
// has a  given Sum
bool checkSubarraySum(int arr[], int n,
                      int k, int sum)
{
    // Check for first window
    int curr_sum = 0;
    for (int i=0; i<k; i++)
       curr_sum += arr[i];   
    if (curr_sum == sum)
        return true;
  
    // Consider remaining blocks ending with j
    for (int j = k; j < n; j++) {
        curr_sum = curr_sum + arr[j] - arr[j-k];
        if (curr_sum == sum) 
            return true;        
    }
    return false;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
    int k = 4;
    int sum = 18;
  
    int n = sizeof(arr) / sizeof(arr[0]);
  
    if (checkSubarraySum(arr, n, k, sum))
        cout << "YES";
    else
        cout << "NO";
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check if any Subarray of size 
// K has a given Sum
  
class GFG{
// Function to check if any Subarray of size K
// has a given Sum
static boolean checkSubarraySum(int[] arr, int n,
                    int k, int sum)
{
    // Check for first window
    int curr_sum = 0;
    for (int i=0; i<k; i++)
    curr_sum += arr[i]; 
    if (curr_sum == sum)
        return true;
  
    // Consider remaining blocks ending with j
    for (int j = k; j < n; j++) {
        curr_sum = curr_sum + arr[j] - arr[j-k];
        if (curr_sum == sum) 
            return true;     
    }
    return false;
}
  
// Driver code
public static void main(String[] args)
{
    int[] arr=new int[]{ 1, 4, 2, 10, 2, 3, 1, 0, 20 };
    int k = 4;
    int sum = 18;
  
    int n = arr.length;
  
    if (checkSubarraySum(arr, n, k, sum))
        System.out.println("YES");
    else
        System.out.println("NO");
  
}
}
// This code is contributed by mits

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to check if any
# Subarray of size K has a given Sum 
  
# Function to check if any Subarray 
# of size K has a given Sum 
def checkSubarraySum(arr, n, 
                     k, sumV):
    # Check for first window 
    curr_sum = 0
    for i in range(0, k): 
        curr_sum += arr[i] 
    if (curr_sum == sumV): 
        return true
  
    # Consider remaining blocks 
    # ending with j 
    for j in range(k, n): 
        curr_sum = (curr_sum + arr[j] - 
                               arr[j - k]) 
        if (curr_sum == sumV) :
            return True    
      
    return False
  
# Driver code 
arr = [ 1, 4, 2, 10, 2,
        3, 1, 0, 20
k = 4
sumV = 18
  
n = len(arr)
  
if (checkSubarraySum(arr, n, k, sumV)): 
    print("YES")
else:
    print( "NO"
  
# This code is contributed 
# by Yatin Gupta

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to check if any Subarray of size 
// K has a given Sum
using System;
  
class GFG{
// Function to check if any Subarray of size K
// has a given Sum
static bool checkSubarraySum(int[] arr, int n,
                    int k, int sum)
{
    // Check for first window
    int curr_sum = 0;
    for (int i=0; i<k; i++)
    curr_sum += arr[i]; 
    if (curr_sum == sum)
        return true;
  
    // Consider remaining blocks ending with j
    for (int j = k; j < n; j++) {
        curr_sum = curr_sum + arr[j] - arr[j-k];
        if (curr_sum == sum) 
            return true;     
    }
    return false;
}
  
// Driver code
static void Main()
{
    int[] arr=new int[]{ 1, 4, 2, 10, 2, 3, 1, 0, 20 };
    int k = 4;
    int sum = 18;
  
    int n = arr.Length;
  
    if (checkSubarraySum(arr, n, k, sum))
        Console.WriteLine("YES");
    else
        Console.WriteLine("NO");
  
}
}
// This code is contributed by mits

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to check if any 
// Subarray of size K has a given Sum
  
// Function to check if any Subarray 
// of size K has a given Sum
function checkSubarraySum($arr, $n
                          $k, $sum)
{
    // Check for first window
    $curr_sum = 0;
    for ($i = 0; $i < $k; $i++)
    $curr_sum += $arr[$i]; 
    if ($curr_sum == $sum)
        return true;
  
    // Consider remaining blocks 
    // ending with j
    for ($j = $k; $j < $n; $j++) 
    {
        $curr_sum = $curr_sum + $arr[$j] -
                                $arr[$j - $k];
        if ($curr_sum == $sum
            return true;     
    }
    return false;
}
  
// Driver code
$arr = array( 1, 4, 2, 10, 
              2, 3, 1, 0, 20 );
$k = 4;
$sum = 18;
  
$n = count($arr);
  
if (checkSubarraySum($arr, $n, $k, $sum))
    echo "YES";
else
    echo "NO";
  
// This code is contributed
// by inder_verma
?>

chevron_right


Output:

YES

Time Complexity: O(n)



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.