Subarray with Given Sum
Last Updated :
14 Aug, 2024
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);
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);
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)
Please Login to comment...