Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Print all subarrays with sum in a given range
Next article icon

Find all subarrays with sum in the given range

Last Updated : 20 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an unsorted array of size, N. Find subarrays that add to a sum in the given range L-R.

Examples:

Input: arr[] = {2, 3, 5, 8}, L = 4, R = 13
Output: The indexes of subarrays are {0, 1}, {0, 2}, {1, 2}, {2, 2}, {2, 3}, {3, 3}

Input: arr[] = {1, 4, 6}, L = 3, R = 8
Output: The indexes of subarrays are {0, 1}, {1, 1}, {2, 2}

Naive approach: Follow the given steps to solve the problem using this approach:

  • Generate every possible subarray using two loops
  • If the sum of that subarray lies in the range [L, R], then push the starting and ending index into the answer array
  • Print the subarrays
     

Below is the implementation of the above approach:  

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find subarrays with sum
// in the given range
void findSubarrays(vector<int> &arr, vector<pair<int,int>> &ans, int L, int R)
{
    int N = arr.size();
 
      for(int i=0; i<N; i++)
    {
        int sum = 0;
        for(int j=i; j<N; j++)
        {
            sum += arr[j];
           
              // If the sum is in the range then
              // insert it into the answer
            if(sum >= L && sum <= R)
                ans.push_back({i, j});
        }
    }
}
 
void printSubArrays(vector<pair<int,int>> &ans)
{
    int size = ans.size();
      for(int i=0; i<size; i++)
        cout<<ans[i].first<<" "<<ans[i].second<<endl;
}
 
// Driver Code
int main()
{
    vector<int> arr = {2, 3, 5, 8};
    int L = 4, R = 13;
      vector<pair<int,int>> ans;
     
    // Function call
    findSubarrays(arr, ans, L, R);
      printSubArrays(ans);
   
    return 0;
}
 
 

Java




// Java program for the above approach
import java.io.*;
 
class GFG {
 
  // Function to find subarrays with sum
  // in the given range
  static void findSubarrays(int arr[], int N, int L,
                            int R)
  {
 
    for (int i = 0; i < N; i++) {
      int sum = 0;
      for (int j = i; j < N; j++) {
        sum += arr[j];
 
        // If the sum is in the range then
        // insert it into the answer
        if (sum >= L && sum <= R)
          System.out.println(i + " " + j);
      }
    }
  }
 
  public static void main(String[] args)
  {
    int N = 4;
    int arr[] = { 2, 3, 5, 8 };
    int L = 4, R = 13;
 
    // Function call
    findSubarrays(arr, N, L, R);
  }
}
 
// This code is contributed by mudit148.
 
 

Python3




# Python3 program for the above approach
 
# Function to find subarrays with sums
# in the given range
def findSubarrays(arr, N, L, R):
     
    for i in range(N):
        sums = 0;
        for j in range(i, N):
            sums += arr[j];
 
            # If the sums is in the range then
            # insert it into the answer
            if (sums >= L and sums <= R):
                print(i, j);
         
N = 4;
arr = [ 2, 3, 5, 8 ];
L = 4
R = 13;
 
# Function call
findSubarrays(arr, N, L, R);
 
# This code is contributed by phasing17.
 
 

C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
class GFG {
 
  // Function to find subarrays with sum
  // in the given range
  static void findSubarrays(int[] arr, int N, int L,
                            int R)
  {
 
    for (int i = 0; i < N; i++) {
      int sum = 0;
      for (int j = i; j < N; j++) {
        sum += arr[j];
 
        // If the sum is in the range then
        // insert it into the answer
        if (sum >= L && sum <= R)
          Console.WriteLine(i + " " + j);
      }
    }
  }
 
  public static void Main(string[] args)
  {
    int N = 4;
    int[] arr = { 2, 3, 5, 8 };
    int L = 4, R = 13;
 
    // Function call
    findSubarrays(arr, N, L, R);
  }
}
 
// This code is contributed by phasing17.
 
 

Javascript




// JS program for the above approach
 
// Function to find subarrays with sum
// in the given range
function findSubarrays(arr, N, L, R)
{
 
    for (let i = 0; i < N; i++) {
        let sum = 0;
        for (let j = i; j < N; j++) {
            sum += arr[j];
 
            // If the sum is in the range then
            // insert it into the answer
            if (sum >= L && sum <= R)
                console.log(i + " " + j);
        }
    }
}
 
let N = 4;
let arr = [ 2, 3, 5, 8 ];
let L = 4, R = 13;
 
// Function call
findSubarrays(arr, N, L, R);
 
// This code is contributed by phasing17.
 
 
Output
0 1 0 2 1 2 2 2 2 3 3 3

Time complexity: O(N2)
Auxiliary Space: O(N2)



Next Article
Print all subarrays with sum in a given range

A

Alexandru Cosmin Vlajoaga
Improve
Article Tags :
  • Arrays
  • DSA
  • Misc
  • sliding-window
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Misc
  • sliding-window

Similar Reads

  • Print all subarrays with sum in a given range
    Given an array arr[] of positive integers and two integers L and R defining the range [L, R]. The task is to print the subarrays having sum in the range L to R. Examples: Input: arr[] = {1, 4, 6}, L = 3, R = 8Output: {1, 4}, {4}, {6}.Explanation: All the possible subarrays are the following{1] with
    5 min read
  • Count subarrays with non-zero sum in the given Array
    Given an array arr[] of size N, the task is to count the total number of subarrays for the given array arr[] which have a non-zero-sum.Examples: Input: arr[] = {-2, 2, -3} Output: 4 Explanation: The subarrays with non zero sum are: [-2], [2], [2, -3], [-3]. All possible subarray of the given input a
    7 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 l
    15+ min read
  • Find all subarray index ranges in given Array with set bit sum equal to X
    Given an array arr (1-based indexing) of length N and an integer X, the task is to find and print all index ranges having a set bit sum equal to X in the array. Examples: Input: A[] = {1 4 3 5 7}, X = 4Output: (1, 3), (3, 4)Explanation: In the above array subarray having set bit sum equal to X (= 4)
    15 min read
  • Find maximum sum by replacing the Subarray in given range
    Given an array arr[], the task is to find the maximum sum possible such that any subarray of the indices from [l, r] i.e all subarray elements from arr[l] to arr[r] can be replaced with |arr[l] - arr[r]| any number of times. Examples: Input: arr[] = { 9, 1}Output: 16Explanation: The subarray [l, r]
    9 min read
  • 2 Sum - Find All Pairs With Given Sum
    Given an array arr[] and a target value, the task is to find all possible indices (i, j) of pairs (arr[i], arr[j]) whose sum is equal to target and i != j. We can return pairs in any order, but all the returned pairs should be internally sorted, that is for any pair(i, j), i should be less than j. E
    9 min read
  • Find the longest Subarray with equal Sum and Product
    Given an array arr[] of N integers, the task is to find the length of the longest subarray where the sum of the elements in the subarray is equal to the product of the elements in the subarray. Examples: Input: arr[] = [1, 2, 1, 2, 2, 5, 6, 24]Output: 5Explanation: The subarray [1, 2, 1, 2, 2] has a
    11 min read
  • Count maximum non-overlapping subarrays with given sum
    Given an array arr[] consisting of N integers and an integer target, the task is to find the maximum number of non-empty non-overlapping subarrays such that the sum of array elements in each subarray is equal to the target. Examples: Input: arr[] = {2, -1, 4, 3, 6, 4, 5, 1}, target = 6Output: 3Expla
    7 min read
  • Smallest subarray with positive sum for all indices
    Given an array arr[] of size N. The task is to determine the minimum length of a subarray starting from index i, such that the sum of the subarray is strictly greater than 0. Calculate the length for all i's in the range 1 to N. If no such subarray exists, then return 0. Examples: Input: N = 3, arr[
    8 min read
  • Subarray with Given Sum
    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 exi
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences