Given an array arr[] consisting of N integers, the task is to find the length of the smallest subarray with sum equal to K.
Examples:
Input: arr[] = {2, 4, 6, 10, 2, 1}, K = 12
Output: 2
Explanation:
All possible subarrays with sum 12 are {2, 4, 6} and {10, 2}.Input: arr[] = { 1, 2, 4, 3, 2, 4, 1 }, K = 7
Output: 2
Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and for each subarray, check if its sum is equal to K or not. Print the minimum length of all such subarray.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be further optimized using the Prefix Sum technique and HashMap. Follow the steps below to solve the problem:
- Compute the prefix sum for every index and store (index, prefix sum) as key-value pairings in the map.
- Traverse over prefix sum array and calculate the difference between prefix sum and the required sum.
- If the difference value exists in the HashMap then it means that there exists a subarray having sum equal to K, then compare the length of the subarray with the minimum length obtained and update the minimum length accordingly.
Below is the implementation of the above approach:
C++
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std;// Function to find the length of the// smallest subarray with sum Kint subArraylen(int arr[], int n, int K){ // Stores the frequency of // prefix sums in the array unordered_map<int, int> mp; mp[arr[0]] = 0; for (int i = 1; i < n; i++) { arr[i] = arr[i] + arr[i - 1]; mp[arr[i]] = i; } // Initialize len as INT_MAX int len = INT_MAX; for (int i = 0; i < n; i++) { // If sum of array till i-th // index is less than K if (arr[i] < K) // No possible subarray // exists till i-th index continue; else { // Find the exceeded value int x = arr[i] - K; // If exceeded value is zero if (x == 0) len = min(len, i); if (mp.find(x) == mp.end()) continue; else { len = min(len, i - mp[x]); } } } return len;}// Driver Codeint main(){ int arr[] = { 1, 2, 4, 3, 2, 4, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 7; int len = subArraylen(arr, n, K); if (len == INT_MAX) { cout << "-1"; } else { cout << len << endl; } return 0;} |
Java
// Java Program to implement// the above approachimport java.util.*;class GFG{// Function to find the length of the// smallest subarray with sum Kstatic int subArraylen(int arr[], int n, int K){ // Stores the frequency of // prefix sums in the array HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); mp.put(arr[0], 0); for (int i = 1; i < n; i++) { arr[i] = arr[i] + arr[i - 1]; mp.put(arr[i], i); } // Initialize len as Integer.MAX_VALUE int len = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { // If sum of array till i-th // index is less than K if (arr[i] < K) // No possible subarray // exists till i-th index continue; else { // Find the exceeded value int x = K - arr[i]; // If exceeded value is zero if (x == 0) len = Math.min(len, i); if (mp.containsValue(x)) continue; else { len = Math.min(len, i ); } } } return len;}// Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 4, 3, 2, 4, 1 }; int n = arr.length; int K = 7; int len = subArraylen(arr, n, K); if (len == Integer.MAX_VALUE) { System.out.print("-1"); } else { System.out.print(len + "\n"); }}}// This code is contributed by Rohit_ranjan |
Python3
# Python3 program to implement# the above approachfrom collections import defaultdictimport sys# Function to find the length of the# smallest subarray with sum Kdef subArraylen(arr, n, K): # Stores the frequency of # prefix sums in the array mp = defaultdict(lambda : 0) mp[arr[0]] = 0 for i in range(1, n): arr[i] = arr[i] + arr[i - 1] mp[arr[i]] = i # Initialize ln ln = sys.maxsize for i in range(n): # If sum of array till i-th # index is less than K if(arr[i] < K): # No possible subarray # exists till i-th index continue else: # Find the exceeded value x = K - arr[i] # If exceeded value is zero if(x == 0): ln = min(ln, i) if(x in mp.keys()): continue else: ln = min(ln, i - mp[x]) return ln# Driver Codearr = [ 1, 2, 4, 3, 2, 4, 1 ]n = len(arr)K = 7ln = subArraylen(arr, n, K)# Function callif(ln == sys.maxsize): print("-1")else: print(ln)# This code is contributed by Shivam Singh |
C#
// C# Program to implement// the above approachusing System;using System.Collections.Generic;class GFG{// Function to find the length of the// smallest subarray with sum Kstatic int subArraylen(int []arr, int n, int K){ // Stores the frequency of // prefix sums in the array Dictionary<int, int> mp = new Dictionary<int, int>(); mp.Add(arr[0], 0); for (int i = 1; i < n; i++) { arr[i] = arr[i] + arr[i - 1]; mp.Add(arr[i], i); } // Initialize len as int.MaxValue int len = int.MaxValue; for (int i = 0; i < n; i++) { // If sum of array till i-th // index is less than K if (arr[i] < K) // No possible subarray // exists till i-th index continue; else { // Find the exceeded value int x = K - arr[i]; // If exceeded value is zero if (x == 0) len = Math.Min(len, i); if (mp.ContainsValue(x)) continue; else { len = Math.Min(len, i ); } } } return len;}// Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 4, 3, 2, 4, 1 }; int n = arr.Length; int K = 7; int len = subArraylen(arr, n, K); if (len == int.MaxValue) { Console.Write("-1"); } else { Console.Write(len + "\n"); }}}// This code is contributed by Rohit_ranjan |
2
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Smallest pair of indices with product of subarray co-prime with product of the subarray on the left or right
- First subarray having sum at least half the maximum sum of any subarray of size K
- Smallest subarray whose sum is multiple of array size
- Smallest subarray from a given Array with sum greater than or equal to K
- Smallest subarray from a given Array with sum greater than or equal to K | Set 2
- Maximum sum of smallest and second smallest in an array
- Maximize the subarray sum after multiplying all elements of any subarray with X
- Maximum length of subarray such that sum of the subarray is even
- Count of subarray that does not contain any subarray with sum 0
- Smallest subarray with sum greater than a given value
- Smallest sum contiguous subarray
- Smallest sum contiguous subarray | Set-2
- Length of Smallest subarray in range 1 to N with sum greater than a given value
- Smallest subarray of size greater than K with sum greater than a given value
- Length of smallest subarray to be removed to make sum of remaining elements divisible by K
- Smallest subarray whose product leaves remainder K when divided by size of the array
- Smallest subarray which upon repetition gives the original array
- Size of smallest subarray to be removed to make count of array elements greater and smaller than K equal
- Length of smallest subarray to be removed such that the remaining array is sorted
- Find the smallest and second smallest elements in an array
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.

