Skip to content
Related Articles

Related Articles

Smallest Subarray with Sum K from an Array
  • Difficulty Level : Medium
  • Last Updated : 26 Sep, 2020

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:
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:

  1. Compute the prefix sum for every index and store (index, prefix sum) as key-value pairings in the map.
  2. Traverse over prefix sum array and calculate the difference between prefix sum and the required sum.
  3. 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 K
int 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 Code
int 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 approach
import java.util.*;
class GFG{
 
// Function to find the length of the
// smallest subarray with sum K
static 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 Code
public 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 approach
from collections import defaultdict
import sys
 
# Function to find the length of the
# smallest subarray with sum K
def 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 Code
arr = [ 1, 2, 4, 3, 2, 4, 1 ]
n = len(arr)
 
K = 7
 
ln = subArraylen(arr, n, K)
 
# Function call
if(ln == sys.maxsize):
    print("-1")
else:
    print(ln)
 
# This code is contributed by Shivam Singh

C#




// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the length of the
// smallest subarray with sum K
static 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 Code
public 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
Output
2

Time Complexity: O(NlogN)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :