Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Subarray of size k with given sum
Next article icon

Subarray of size k with given sum

Last Updated : 01 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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++
// 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; } 
Java
// 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 
Python3
# 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 
C#
// 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 
PHP
<?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 ?> 
JavaScript
<script>     // Javascript 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 (let i = 0; i < n - k + 1; i++)         {              let current_sum = 0;              // Consider each             // subarray of size k             for (let j = 0; j < k; j++)                 current_sum = current_sum + arr[i + j];              if (current_sum == sum)                 return true;             }         return false;     }          let arr = [ 1, 4, 2, 10, 2, 3, 1, 0, 20 ];     let k = 4;     let sum = 18;       let n = arr.length;       if (checkSubarraySum(arr, n, k, sum))         document.write("YES");     else         document.write("NO");  // This code is contributed by mukesh07. </script> 

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. 

Implementation:

C++
// 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; } 
Java
// 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 
Python3
# 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 
C#
// 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 
PHP
<?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 ?> 
JavaScript
<script> // Javascript 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     let curr_sum = 0;     for (let i = 0; i < k; i++)     curr_sum += arr[i];     if (curr_sum == sum)         return true;      // Consider remaining blocks     // ending with j     for (let j = k; j < n; j++)     {         curr_sum = curr_sum + arr[j] -                                 arr[j - k];         if (curr_sum == sum)             return true;         }     return false; }  // Driver code let arr = new Array( 1, 4, 2, 10,             2, 3, 1, 0, 20 ); let k = 4; let sum = 18;  let n = arr.length;  if (checkSubarraySum(arr, n, k, sum))     document.write("YES"); else     document.write("NO");  // This code is contributed // by _saurabh_jaiswal </script> 

Output
YES

Time Complexity: O(n)

Related Topic: Subarrays, Subsequences, and Subsets in Array


Next Article
Subarray of size k with given sum

B

barykrg
Improve
Article Tags :
  • Misc
  • DSA
  • Arrays
  • subarray
  • sliding-window
Practice Tags :
  • Arrays
  • Misc
  • sliding-window

Similar Reads

    Subarray with exactly K positive sum
    Given two integer values N and K, the task is to create an array A of N integers such that number of the total positive sum subarrays is exactly K and the remaining subarrays have a negative sum (-1000 ≤ A[i] ≤ 1000). Examples: Input: N = 4, K=5Output: 2 2 -1 -1000Explanation:Positive Sum Subarrays:
    8 min read
    Subarray with no pair sum divisible by K
    Given an array of N non-negative integers, task is to find the maximum size of a subarray such that the pairwise sum of the elements of this subarray is not divisible by a given integer, K. Also, print this subarray as well. If there are two or more subarrays that follow the above stated condition,
    13 min read
    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 Sub
    11 min read
    Longest Subarray With Sum K
    Given an array arr[] of size n containing integers, the task is to find the length of the longest subarray having sum equal to the given value k.Note: If there is no subarray with sum equal to k, return 0.Examples: Input: arr[] = [10, 5, 2, 7, 1, -10], k = 15Output: 6Explanation: Subarrays with sum
    10 min read
    Maximum count of distinct sized subarrays with given sum
    Given a binary array arr[] of N integers, the task is to find the maximum count of distinct sized subarrays such that the sum of each subarray is K. Example: Input: arr[] = {0, 1, 1 , 0}, K = 2Output: 3Explanation: The subset {{0, 1, 1, 0}, {0, 1, 1}, {1, 1}} is the subset of 3 subarrays such that t
    7 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