The Wayback Machine - https://web.archive.org/web/20240818165439/https://www.geeksforgeeks.org/find-subarray-with-given-sum/
Open In App

Subarray with Given Sum

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a 1-based indexing array arr[] of integers and an integer sum. You mainly need to return the left and right indexes(1-based indexing) of that subarray. In case of multiple subarrays, return the subarray indexes which come first on moving from left to right. If no such subarray exists return an array consisting of element -1.

Examples: 

Input: arr[] = { 15, 2, 4, 8, 9, 5, 10, 23}, sum = 23
Output: 2 5
Explanation: Sum of elements between indices 2 and 5 is 2 + 4 + 8 + 9 = 23

Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7
Output: 2 5
Explanation: Sum of elements between indices 1 and 4 is 4 + 0 + 0 + 3 = 7

Input: arr[] = {1, 4}, sum = 0
Output: -1
Explanation: There is no subarray with 0 sum

[Naive] Using Nested loop – O(N^2) time and O(1) auxiliary space

The very basic idea is to use a nested loop where the outer loop picks a starting element, and the inner loop calculates the cumulative sum of elements starting from this element.

For each starting element, the inner loop iterates through subsequent elements and adding each element to the cumulative sum until the given sum is found or the end of the array is reached. If at any point the cumulative sum equals the given sum, then return starting and ending indices (1-based). If no such sub-array is found after all iterations, then return -1.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find a continuous sub-array which adds up to
// a given number.
vector<int> subarraySum(vector<int> arr, int sum)
{
    // To store the result
    vector<int> res;
    int n = arr.size();

    // Pick a starting point for a 
    // subarray
    for (int s = 0; s < n; s++)
    {
        int curr = 0;
      
        // Consider all ending points
        // for the picked starting point 
        for (int e = s; e < n; e++)
        {
            curr += arr[e];
            if (curr == sum)
            {
                res.push_back(s + 1);
                res.push_back(e + 1);
                return res;
            }
        }
    }
    return {-1}; // If no subarray is found
}

// Driver Code
int main()
{
    vector<int> arr = {15, 2, 4, 8, 9, 5, 10, 23};
    int sum = 23;
    vector<int> result = subarraySum(arr, sum);
    for (auto i : result)
        cout << i << " ";
    return 0;
}
Java
import java.util.ArrayList;

public class Main {
    // Function to find a continuous sub-array which adds up
    // to a given number.
    static ArrayList<Integer> subarraySum(int[] arr, int n,
                                          long sum)
    {

        // To store the result
        ArrayList<Integer> res = new ArrayList<>();

        // Flag to indicate if the subarray is found
        boolean flag = false;

        for (int i = 0; i < n; i++) {

            // Initialize the current sum
            int currentSum = arr[i];

            // Check if the single element is the sum
            if (currentSum == sum) {
                res.add(i + 1);
                res.add(i + 1);
                flag = true;
                break;
            }
            else {
                // Try all subarrays starting with 'i'
                for (int j = i + 1; j < n; j++) {
                    currentSum += arr[j];

                    if (currentSum == sum) {
                        res.add(i + 1);
                        res.add(j + 1);
                        flag = true;
                        break;
                    }
                }
                if (flag)
                    break;
            }
        }
        if (flag)
            return res;
        res.add(-1); // If no subarray is found
        return res;
    }

    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 15, 2, 4, 8, 9, 5, 10, 23 };
        int n = arr.length;
        long sum = 23;
        ArrayList<Integer> result
            = subarraySum(arr, n, sum);
        for (int i : result)
            System.out.print(i + " ");
    }
}
Python
def subarray_sum(arr, n, target_sum):

    # To store the result
    res = []

    # Flag to indicate if the subarray is found
    flag = False

    for i in range(n):
        current_sum = arr[i]  # Initialize the current sum

        # Check if the single element is the sum
        if current_sum == target_sum:
            res.append(i + 1)
            res.append(i + 1)
            flag = True
            break
        else:
            # Try all subarrays starting with 'i'
            for j in range(i + 1, n):
                current_sum += arr[j]

                if current_sum == target_sum:
                    res.append(i + 1)
                    res.append(j + 1)
                    flag = True
                    break
            if flag:
                break
    if flag:
        return res
    return [-1]  # If no subarray is found


# Driver Code
if __name__ == "__main__":
    arr = [15, 2, 4, 8, 9, 5, 10, 23]
    n = len(arr)
    target_sum = 23
    result = subarray_sum(arr, n, target_sum)
    for i in result:
        print(i, end=" ")
C#
using System;
using System.Collections.Generic;

class Program {
    // Function to find a continuous sub-array which adds up
    // to a given number.
    static List<int> SubarraySum(int[] arr, int n, long sum)
    {

        // To store the result
        List<int> res = new List<int>();

        // Flag to indicate if the subarray is found
        bool flag = false;

        for (int i = 0; i < n; i++) {

            // Initialize the current sum
            int currentSum = arr[i];

            // Check if the single element is the sum
            if (currentSum == sum) {
                res.Add(i + 1);
                res.Add(i + 1);
                flag = true;
                break;
            }
            else {
                // Try all subarrays starting with 'i'
                for (int j = i + 1; j < n; j++) {
                    currentSum += arr[j];

                    if (currentSum == sum) {
                        res.Add(i + 1);
                        res.Add(j + 1);
                        flag = true;
                        break;
                    }
                }
                if (flag)
                    break;
            }
        }
        if (flag)
            return res;
        return new List<int>{
            -1
        }; // If no subarray is found
    }

    // Driver Code
    static void Main()
    {
        int[] arr = { 15, 2, 4, 8, 9, 5, 10, 23 };
        int n = arr.Length;
        long sum = 23;
        List<int> result = SubarraySum(arr, n, sum);
        foreach(int i in result) Console.Write(i + " ");
    }
}
JavaScript
function subarraySum(arr, n, sum) {
  // To store the result
  let res = [];

  // Flag to indicate if the subarray is found
  let flag = false;

  for (let i = 0; i < n; i++) {
    // Initialize the current sum
    let currentSum = arr[i];

    // Check if the single element is the sum
    if (currentSum === sum) {
      res.push(i + 1);
      res.push(i + 1);
      flag = true;
      break;
    } else {
      // Try all subarrays starting with 'i'
      for (let j = i + 1; j < n; j++) {
        currentSum += arr[j];

        if (currentSum === sum) {
          res.push(i + 1);
          res.push(j + 1);
          flag = true;
          break;
        }
      }
      if (flag) break;
    }
  }
  if (flag) return res;
  return [-1]; // If no subarray is found
}

// Driver Code
let arr = [15, 2, 4, 8, 9, 5, 10, 23];
let n = arr.length;
let sum = 23;
let result = subarraySum(arr, n, sum);
for (let i of result) console.log(i);

Output
2 5 

Time Complexity: O(N2), Trying all subarrays from every index, used nested loop for the same
Auxiliary Space: O(1). 

[ Sliding Window] O(N) time and O(1) auxiliary space

The idea is simple, as we know that all the elements in subarray are positive so, If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray will be equal to the given sum. So the Idea is to use a similar approach to a sliding window. 

  • Start with an empty window 
  • add elements to the window while the current sum is less than sum 
  • If the sum is greater than sum, remove elements from the start of the current window.
  • If current sum becomes same as sum, return the result


C++
#include <iostream>
#include <vector>
using namespace std;

vector<int> subarraySum(vector<int>& arr, int sum) {
  
    int s = 0, e = 0;  // Initialize window
  
    vector<int> res;

    int curr = 0;
    for (int i = 0; i < arr.size(); i++) {
        curr += rr[i];

        // If current sum becomes more or equal,
        // set end and try adjusting start
        if (curr >= sum) {
            e = i;

            // While current sum is more
            // remove, starting elements of
            // current window
            while (curr > sum && s < e) {
                curr -= arr[s];
                ++s;
            }

            // If we found a subraay
            if (curr == sum) {
                res.push_back(s + 1);
                res.push_back(e + 1);
                return res;
            }
        }
    }

    return {-1}; // Never found a subarray
}

int main() {
    vector<int> arr = {15, 2, 4, 8, 9, 5, 10, 23};
    int sum = 23;
    vector<int> res = subarraySum(arr, sum);
    for (auto i : res)
        cout << i << " ";
    return 0;
}
Java
import java.util.ArrayList;

public class SubarraySum {

    // Function to find a continuous sub-array which adds up to a given number.
    public static ArrayList<Integer> subarraySum(int[] arr, int n, long sum) {
        int last = 0;
        int start = 0;
        long currsum = 0;
        boolean flag = false;
        ArrayList<Integer> res = new ArrayList<>();

        // Iterate over the array
        for (int i = 0; i < n; i++) {
            // Store sum up to current element
            currsum += arr[i];

            // Check if current sum is greater than or equal to given number
            if (currsum >= sum) {
                last = i;

                // Start from starting index till current index
                while (sum < currsum && start < last) {
                    // Subtract the element from left
                    currsum -= arr[start];
                    ++start;
                }

                // If current sum becomes equal to given number
                if (currsum == sum) {
                    res.add(start + 1);
                    res.add(last + 1);
                    flag = true;
                    break;
                }
            }
        }

        // If no subarray is found, store -1 in result
        if (!flag)
            res.add(-1);

        // Return the result
        return res;
    }

    // Driver Code
    public static void main(String[] args) {
        int[] arr = {15, 2, 4, 8, 9, 5, 10, 23};
        int n = arr.length;
        int sum = 23;
        ArrayList<Integer> res = subarraySum(arr, n, sum);
        for (int i : res)
            System.out.print(i + " ");
    }
}
Python
def subarray_sum(arr, n, sum):
    last = 0
    start = 0
    currsum = 0
    flag = False
    res = []

    # Iterate over the array
    for i in range(n):
        # Store sum up to current element
        currsum += arr[i]

        # Check if current sum is greater than or equal to given number
        if currsum >= sum:
            last = i

            # Start from starting index till current index
            while sum < currsum and start < last:
                # Subtract the element from left
                currsum -= arr[start]
                start += 1

            # If current sum becomes equal to given number
            if currsum == sum:
                res.append(start + 1)
                res.append(last + 1)
                flag = True
                break

    # If no subarray is found, store -1 in result
    if not flag:
        res.append(-1)

    # Return the result
    return res


# Driver Code
arr = [15, 2, 4, 8, 9, 5, 10, 23]
n = len(arr)
sum = 23
res = subarray_sum(arr, n, sum)
for i in res:
    print(i, end=" ")
C#
using System;
using System.Collections.Generic;

class Program {
    // Function to find a continuous sub-array which adds up to a given number.
    static List<int> SubarraySum(int[] arr, int n, long sum) {
        int last = 0;
        int start = 0;
        long currsum = 0;
        bool flag = false;
        List<int> res = new List<int>();

        // Iterate over the array
        for (int i = 0; i < n; i++) {
            // Store sum up to current element
            currsum += arr[i];

            // Check if current sum is greater than or equal to given number
            if (currsum >= sum) {
                last = i;

                // Start from starting index till current index
                while (sum < currsum && start < last) {
                    // Subtract the element from left
                    currsum -= arr[start];
                    ++start;
                }

                // If current sum becomes equal to given number
                if (currsum == sum) {
                    res.Add(start + 1);
                    res.Add(last + 1);
                    flag = true;
                    break;
                }
            }
        }

        // If no subarray is found, store -1 in result
        if (!flag)
            res.Add(-1);

        // Return the result
        return res;
    }

    // Driver Code
    static void Main() {
        int[] arr = { 15, 2, 4, 8, 9, 5, 10, 23 };
        int n = arr.Length;
        int sum = 23;
        List<int> res = SubarraySum(arr, n, sum);
        foreach (int i in res)
            Console.Write(i + " ");
    }
}
JavaScript
// Function to find a continuous sub-array which adds up to a given number.
function subarraySum(arr, n, sum) {
    let last = 0;
    let start = 0;
    let currsum = 0;
    let flag = false;
    let res = [];

    // Iterate over the array
    for (let i = 0; i < n; i++) {
        // Store sum up to current element
        currsum += arr[i];

        // Check if current sum is greater than or equal to given number
        if (currsum >= sum) {
            last = i;

            // Start from starting index till current index
            while (sum < currsum && start < last) {
                // Subtract the element from left
                currsum -= arr[start];
                ++start;
            }

            // If current sum becomes equal to given number
            if (currsum == sum) {
                res.push(start + 1);
                res.push(last + 1);
                flag = true;
                break;
            }
        }
    }

    // If no subarray is found, store -1 in result
    if (!flag)
        res.push(-1);

    // Return the result
    return res;
}

// Driver Code
let arr = [15, 2, 4, 8, 9, 5, 10, 23];
let n = arr.length;
let sum = 23;
let res = subarraySum(arr, n, sum);
for (let i of res)
    console.log(i);

Output
2 5 

Time Complexity: O(N), where N is the length of input array
Auxiliary Space: O(1). Since no extra space has been taken.

[ Hashing + Prefix Sum] O(N) time and O(N) Space

The above solution does not work for arrays with negative numbers. To handle all cases, we use hashing and prefix sum. The idea is to store the sum of elements of every prefix of the array in a hashmap, i.e, every index stores the sum of elements up to that index hashmap. So to check if there is a subarray with a sum equal to target_sum, check for every index i, and sum up to that index as curr_sum. If there is a prefix with a sum equal to (curr_sum – target_sum), then the subarray with the given sum is found. Please refer the below article for the complete details.

Find subarray with given sum | Set 2 (Handles Negative Numbers)



Previous Article
Next Article

Similar Reads

First subarray having sum at least half the maximum sum of any subarray of size K
Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K. Examples: Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3 Output: 6 2 1 Explanation: The given array has a maximum possible sum from any subarray of size K is 16 fr
9 min read
Minimum cost to convert all elements of a K-size subarray to 0 from given Ternary Array with subarray sum as cost
Given an array arr[] of N integers, where each array element is either 0, 1, or 2, and an integer K, the task is to print the minimum cost needed to convert all the elements of the array to 0s by selecting a subarray of size K and converting any array element of the subarray to 0 in one operation with the cost equal to the sum of elements of the su
11 min read
Maximum sum subarray having sum less than given sum using Set
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum
7 min read
Maximum sum subarray having sum less than or equal to given sum
Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array. Note: Given array contains only non-negative integers. Examples: Input: arr[] = { 1, 2, 3, 4, 5 } sum = 11Output: 10Subarray having maximum sum is { 1, 2, 3, 4 }Input: arr[] = { 2, 4, 6, 8, 10
10 min read
Maximize the subarray sum after multiplying all elements of any subarray with X
Given an array arr[] of N integers and an integer X. We can choose any sub-array and multiply all its element by X. After multiplication, find the sub-array with the maximum sum. The task is to multiply the sub-array in such a way that the final sub-array sum is maximized. Examples: Input: arr[] = { -3, 8, -2, 1, -6 }, X = -1 Output: 15 Choose the
15+ min read
Find minimum subarray sum for each index i in subarray [i, N-1]
Given an array arr[] of size N, the task is to find the minimum subarray sum in the subarrays [i, N-1] for all i in [0, N-1]. Examples: Input: arr[ ] = {3, -1, -2}Output: -3 -3 -2Explanation: For (i = 1) i.e. {3, -1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 2) i.e. {-1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 3) i
9 min read
Maximize subarray sum by inverting sign of elements of any subarray at most twice
Given an array A of size n, find the maximum subarray sum after applying the given operation at most two times. In one operation, choose any two indices i and j and invert sign of all the elements from index i to index j, i.e, all positive elements in the range i to j become negative and all negative elements become positive. Examples: Input: A[] =
10 min read
Maximize product of min value of subarray and sum of subarray over all subarrays of length K
Given an array arr[] of N integers, the task is to find the maximum possible value of (min * sum) among all possible subarrays having K elements, where min denotes the smallest integer of the subarray and sum denotes the sum of all elements of the subarray. Example: Input: arr[] = {1, 2, 3, 2}, K = 3Output: 14Explanation: For the subarray {2, 3, 2}
7 min read
Count of subarray that does not contain any subarray with sum 0
Given an array arr, the task is to find the total number of subarrays of the given array which do not contain any subarray whose sum of elements is equal to zero. All the array elements may not be distinct.Examples: Input: arr = {2, 4, -6} Output: 5 Explanation: There are 5 subarrays which do not contain any subarray whose elements sum is equal to
11 min read
Queries to multiply the given subarray with given number X and print sum
Given an array arr[] and Q queries where each query contains three integers (l, r, x), the task is to print the sum of the elements in range [l,r] after multiplying each element with x. Query(l, r, x) = arr[l]*x + arr[l+1]*x + .... arr[r-1]*x + arr[r]*x Note: Multiplication with x is done to calculate the answer and it is not updated in the input a
7 min read
Maximum length of subarray such that all elements are equal in the subarray
Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements. Input: arr[] = {1, 2, 3, 4} Output: 1 Explanation: All identical elemen
5 min read
Smallest pair of indices with product of subarray co-prime with product of the subarray on the left or right
Given an array arr[] of length N, the task is to find the smallest pair of indices (i, j) such that the product of elements in the subarray arr[i + 1, j - 1] is co-prime with either the product of the subarray arr[0, i] or that of the subarray arr[j, N]. If no such pair exists, the print "-1". Examples: Input: arr[] = {2, 4, 1, 3, 7}Output: (0, 2)E
12 min read
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print "Impossible". Examples: Input:
12 min read
Maximum subarray sum in O(n) using prefix sum
Given an Array of Positive and Negative Integers, find out the Maximum Subarray Sum in that Array. Examples: Input1 : arr = {-2, -3, 4, -1, -2, 1, 5, -3} Output1 : 7 Input2 : arr = {4, -8, 9, -4, 1, -8, -1, 6} Output2 : 9 Kadane's Algorithm solves this problem using Dynamic Programming approach in linear time. Here is another approach using Dynamic
8 min read
Count the subarray with sum strictly greater than the sum of remaining elements
Given an array arr[] of N positive integers, the task is to count all the subarrays where the sum of subarray elements is strictly greater than the sum of remaining elements. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 6 Explanation: Subarrays are: {1, 2, 3, 4} - sum of subarray = 10, sum of remaining elements {5} = 5 {1, 2, 3, 4, 5} - sum of
12 min read
Create an array of size N with sum S such that no subarray exists with sum S or S-K
Given a number N and an integer S, the task is to create an array of N integers such that sum of all elements equals to S and print an element K where 0 ? K ? S, such that there exists no subarray with sum equals to K or (S - K). If no such array is possible then print "-1".Note: There can be more than one value for K. You can print any one of them
6 min read
Maximum sum subarray of size K with sum less than X
Given an array arr[] and two integers K and X, the task is to find the maximum sum among all subarrays of size K with the sum less than X. Examples: Input: arr[] = {20, 2, 3, 10, 5}, K = 3, X = 20Output: 18Explanation: Subarray of size 3 having maximum sum less than 20 is {3, 10, 5}. Therefore, required output is 18. Input: arr[] = {-5, 8, 7, 2, 10
7 min read
Max sum of Subarray of length N/2 where sum is divisible by N
Given an array, arr[] of size N where N is even, the task is to find the maximum possible sum of the subarray of length N/2 where the sum is divisible by N. Examples: Input: arr[] = {2, 3, 4, 5, 6, 7}, N = 6Output:18Explanation: Here, N = 6, The maximum possible sum of a sublist of length 3 (N/2) is 18 (divisible by 6), which can be obtained by sel
8 min read
Maximum Subarray Sum in a given Range
Given an array of n numbers, the task is to answer the following queries: maximumSubarraySum(start, end) : Find the maximum subarray sum in the range from array index 'start' to 'end'. Also see : Range Query With Update Required Examples: Input : arr[] = {1, 3, -4, 5, -2} Query 1: start = 0, end = 4 Query 2: start = 0, end = 2 Output : 5 4 Explanat
15+ min read
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
10 min read
Maximum subarray sum in array formed by repeating the given array k times
Given an integer k and an integer array arr[] of n elements, the task is to find the largest sub-array sum in the modified array (formed by repeating the given array k times). For example, if arr[] = {1, 2} and k = 3 then the modified array will be {1, 2, 1, 2, 1, 2}. Examples: Input: arr[] = {1, 2}, k = 3 Output: 9 Modified array will be {1, 2, 1,
12 min read
Length of Smallest subarray in range 1 to N with sum greater than a given value
Given two numbers N and S, the task is to find the length of smallest subarray in range (1, N) such that the sum of those chosen numbers is greater than S. Examples: Input: N = 5, S = 11 Output: 3 Explanation: Smallest subarray with sum &gt; 11 = {5, 4, 3} Input: N = 4, S = 7 Output: 3 Explanation: Smallest subarray with sum &gt; 7 = {4, 3, 2} Naiv
9 min read
Check if a subarray exists with sum greater than the given Array
Given an array of integers arr, the task is to check if there is a subarray (except the given array) such that the sum of its elements is greater than or equal to the sum of elements of the given array. If no such subarray is possible, print No, else print Yes.Examples: Input: arr = {5, 6, 7, 8} Output: No Explanation: There isn't any subarray of t
7 min read
Count of elements which is the sum of a subarray of the given Array
Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3 =&gt; arr[0-1] =&gt; 1 + 2 = 3 arr[4] = 5 =&gt; ar
7 min read
Reverse a subarray to maximize sum of even-indexed elements of given array
Given an array arr[], the task is to maximize the sum of even-indexed elements by reversing a subarray and print the maximum sum obtained. Examples: Input: arr[] = {1, 2, 1, 2, 1} Output: 5 Explanation: Sum of initial even-indexed elements = a[0] + a[2] + a[4] = 1 + 1 + 1 = 3 Reversing subarray {1, 2, 1, 2} modifies the array to {2, 1, 2, 1, 1}. He
9 min read
Maximize Sum possible by subtracting same value from all elements of a Subarray of the given Array
Given an array a[] consisting of N integers, the task is to find the maximum possible sum that can be achieved by deducting any value, say X, from all elements of a subarray. Examples: Input: N = 3, a[] = {80, 48, 82} Output: 144 Explanation: 48 can be deducted from each array element. Therefore, sum obtained = 48 * 3 = 144Input: N = a[] = {8, 40,
11 min read
Smallest subarray from a given Array with sum greater than or equal to K | Set 2
Given an array A[] consisting of N positive integers and an integer K, the task is to find the length of the smallest subarray with a sum greater than or equal to K. If no such subarray exists, print -1. Examples: Input: arr[] = {3, 1, 7, 1, 2}, K = 11Output: 3Explanation:The smallest subarray with sum ? K(= 11) is {3, 1, 7}. Input: arr[] = {2, 3,
15+ min read
Check if the sum of a subarray within a given range is a perfect square or not
Given an array arr[] of size N and an array range[], the task is to check if the sum of the subarray {range[0], .. , range[1]} is a perfect square or not. If the sum is a perfect square, then print the square root of the sum. Otherwise, print -1. Example : Input: arr[] = {2, 19, 33, 48, 90, 100}, range = [1, 3] Output: 10 Explanation: The sum of el
7 min read
Smallest subarray of size greater than K with sum greater than a given value
Given an array, arr[] of size N, two positive integers K and S, the task is to find the length of the smallest subarray of size greater than K, whose sum is greater than S. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 1, S = 8Output: 2Explanation: Smallest subarray with sum greater than S(=8) is {4, 5}Therefore, the required output is 2. Input: ar
15 min read
Maximum sum of K-length subarray consisting of same number of distinct elements as the given array
Given an array arr[] consisting of N integers and an integer K, the task is to find a subarray of size K with maximum sum and count of distinct elements same as that of the original array. Examples: Input: arr[] = {7, 7, 2, 4, 2, 7, 4, 6, 6, 6}, K = 6Output: 31Explanation: The given array consists of 4 distinct elements, i.e. {2, 4, 6, 7}. The suba
15+ min read
three90RightbarBannerImg