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

Find Subarray with given Sum from Array of non-negative Numbers

Last Updated : 19 Jul, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Given a 1-based indexing array arr[] of non-negative 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

Approaches to find subarray with given sum

[Naive Approach] 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.

Code Implementation:

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 n,
                        long long sum)
{
    // To store the result
    vector<int> res;

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

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

        // Check if the single element is the sum
        if (currentSum == sum) {
            res.push_back(i + 1);
            res.push_back(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.push_back(i + 1);
                    res.push_back(j + 1);
                    flag = true;
                    break;
                }
            }
            if (flag)
                break;
        }
    }
    if (flag)
        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 n = arr.size();
    long long sum = 23;
    vector<int> result = subarraySum(arr, n, 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). 

[Expected Approach] Using 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 subarray 
  • add elements to the subarray until the sum is less than k( given sum). 
  • If the sum is greater than k, remove elements from the start of the current subarray.

Code Implementation:

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

// Function to find a continuous sub-array which adds up to a given number.
vector<int> subarraySum(vector<int>& arr, int n, long long sum) {
    int last = 0;
    int start = 0;
    unsigned long long currsum = 0;
    bool flag = false;
    vector<int> res;

    // 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.push_back(start + 1);
                res.push_back(last + 1);
                flag = true;
                break;
            }
        }
    }

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

    // Return the result
    return res;
}

// Driver Code
int main() {
    vector<int> arr = {15, 2, 4, 8, 9, 5, 10, 23};
    int n = arr.size();
    int sum = 23;
    vector<int> res = subarraySum(arr, n, 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.

How to handle Arrays with Negative Elements?

Please refer the below article for negative element arrays

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





Previous Article
Next Article

Similar Reads

Find subarray with given sum | Set 2 (Handles Negative Numbers)
Given an unsorted array of integers, find a subarray that adds to a given number. If there is more than one subarray with the sum of the given number, print any of them. Examples: Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33Output: Sum found between indexes 2 and 4Explanation: Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33 Input: arr[
13 min read
Largest sum contiguous subarray having only non-negative elements
Given an integer array arr[], the task is to find the largest sum contiguous subarray of non-negative elements and return its sum. Examples: Input: arr[] = {1, 4, -3, 9, 5, -6} Output: 14 Explanation: Subarray [9, 5] is the subarray having maximum sum with all non-negative elements. Input: arr[] = {12, 0, 10, 3, 11} Output: 36 Recommended PracticeM
8 min read
First subarray with negative sum from the given Array
Given an array arr[] consisting of N integers, the task is to find the start and end indices of the first subarray with a Negative Sum. Print "-1" if no such subarray exists. Note: In the case of multiple negative-sum subarrays in the given array, the first subarray refers to the subarray with the lowest starting index. Examples: Input: arr[] = {3,
15+ min read
Longest Subarray of non-negative Integers
Given an array, return the length of the longest subarray of non-negative integers Examples : Input : {2, 3, 4, -1, -2, 1, 5, 6, 3}Output : 4Explanation: The subarray [ 1, 5, 6, 3] has length 4 and contains no negative integers Input : {1, 0, 0, 1, -1, -1, 0, 0, 1, 0}Output : 4Explanation: Subarrays [1, 0, 0, 1] and [0, 0, 1, 0] have equal lengths
9 min read
Find the index in a circular array from which prefix sum is always non-negative
Given a circular array arr[] consisting of N integers, the task is to find the starting index of the circular array such that the prefix sum from that index is always non-negative. If there exists no such index, then print "-1". Examples: Input: arr[] = {3, -6, 7, -1, -4, 5, -1}Output: 2Explanation:Consider the index 2 from where the prefix sum of
6 min read
Find highest frequency of non-negative powers that are same as indices of elements in given Array
Given an array arr[] with N non-negative integers, find the maximum number of elements that are the same non-negative powers of their indices. arr[i] = iX, where X is a non negative number. The task is to return the maximum frequency of X. Example: Input: arr = [1, 1, 4, 17]Output: 2Explanation: The element 1 at index 0, is a power of 0The element
12 min read
Maximum sum of array after removing a positive or negative subarray
Given an array arr[] of N non-zero integers, the task is to find the maximum sum of the array by removing exactly one contiguous set of positive or negative elements. Examples: Input: arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}Output: 4Explanation: Maximum array sum can be obtained by removing subarray arr[0, 1] since arr[0, 1] has same type of elements
7 min read
Find ratio of zeroes, positive numbers and negative numbers in the Array
Given an array a of integers of size N integers, the task is to find the ratio of positive numbers, negative numbers and zeros in the array up to four decimal places. Examples: Input: a[] = {2, -1, 5, 6, 0, -3} Output: 0.5000 0.3333 0.1667 There are 3 positive, 2 negative, and 1 zero. Their ratio would be positive: 3/6 = 0.5000, negative: 2/6 = 0.3
7 min read
Count sequences of given length having non-negative prefix sums that can be generated by given values
Given two integers M and X, the task is to find the number of sequences of length M that can be generated comprising X and -X such that their respective counts are equal and the prefix sum up to each index of the resulting sequence is non-negative. Examples: Input: M = 4, X = 5Output: 2Explanation:There are only 2 possible sequences that have all p
7 min read
Find Array after removing -1 and closest non-negative left element
Given an array arr[] of size N that contains -1 and all positive integers, the task is to modify the array and print the final array after performing the below valid operations: Choose -1 from the array.Remove the closest non-negative element (if there is any) to its left, as well as remove -1 itself. Examples: Input: arr[] = {1, 2, 3, -1, -1, 4, 5
11 min read
three90RightbarBannerImg