Open In App

Smallest Subarray with Sum K from an Array

Last Updated : 20 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers, the task is to find the length of the Smallest subarray with a 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[] = {-8, -8, -3, 8}, K = 5 
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 subarrays. 

C++
// c++ code to implement the above idea
#include <bits/stdc++.h>
using namespace std;

// Function to find the Smallest Subarray with
// Sum K from an Array
int smallestSubarraySumK(vector<int>& arr, int k)
{
    int result = INT_MAX;

    for (int i = 0; i < arr.size(); ++i) {
        int sum = 0;
        for (int j = i; j < arr.size(); j++) {
            sum += arr[j];
            if (sum == k) {
                result = min(result, (j - i + 1));
            }
        }
    }

    // Return result
    return result;
}

// Driver code
int main()
{

    vector<int> arr = { -8, -8, -3, 8 };
    int k = 5;

    int result = smallestSubarraySumK(arr, k);
    if (result == INT_MAX)
        cout << -1;
    else
        cout << result;
    return 0;
}
Java Python3 C# JavaScript

Output
2

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient approach: The above approach can be further optimized using the Prefix Sum technique and Map

Follow the steps below to solve the problem:

  • currPrefixSum will store the prefix sum ending at ith index.
  • Iterate over the array and keep calculating currPrefixSum.
    • Check if, currPrefixSum is equal to K.
      • If yes, then use this length of subarray (currPrefixSum) to minimize the result.
    • Also, check if the required prefix sum (currPrefixSum - K) has been calculated previously or not.
      • If the required prefix sum is calculated previously then find its last occurrence of that prefix sum and use it to calculate the length of the current prefix sum equal to K by (current index - last occurrence of required prefix sum) and use it to minimize the result.
    • Store the currPrefixSum which is ending at ith index into the map.
  • Finally, return the result.
     

Below is the implementation of the above approach:

C++
// c++ code to implement the above idea
#include <bits/stdc++.h>
using namespace std;



// Function to find the Smallest Subarray with
// Sum K from an Array
int smallestSubarraySumK(vector<int> & arr, int k ){

    // Use map here to store the prefixSum ending
    // at ith index.
    unordered_map<long long, int> unmap;
    int n = arr.size();

    // Store the current Prefix sum till ith index;
    long long currPrefixSum = 0;

    // Store the minimum size subarray whose sum is K
    long long result = INT_MAX;

    for(int i = 0; i < n; i++){
        currPrefixSum += arr[i];

        // Check if the current prefix sum is equals to K
        if(currPrefixSum == k){
            long long currLen = i + 1;
            result = min(result, currLen);
        }

        // Required PrefixSum
        long long requirePrefixSum 
            = currPrefixSum - k;

        // Check if there exist any required
        // Prefix Sum or not
        if(unmap.count(requirePrefixSum)){
            long long foundIdx =
                unmap[requirePrefixSum];
            long long currIdx = i;

            result = min(result, 
                           currIdx - foundIdx);
        }

        // Store the current prefix sum ending
        // at i
        unmap[currPrefixSum] = i;
    }

    if(result >= INT_MAX) return -1;
    // return the result
    return result;
}

 
// Driver code
int main(){
    
    vector<int> arr = {-8, -8, -3, 8};
    int k = 5;

    cout << smallestSubarraySumK(arr, k);
    return 0;
}
Java Python3 C# JavaScript

Output
2

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


Next Article

Similar Reads