The Wayback Machine - https://web.archive.org/web/20240818163938/https://www.geeksforgeeks.org/generating-subarrays-using-recursion/
Open In App

Generating subarrays using recursion

Last Updated : 11 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array, generate all the possible subarrays of the given array using recursion.

Examples: 

Input : [1, 2, 3]
Output : [1], [1, 2], [2], [1, 2, 3], [2, 3], [3]

Input : [1, 2]
Output : [1], [1, 2], [2]

We have discussed iterative program to generate all subarrays. In this post, recursive is discussed.

Approach: We use two pointers start and end to maintain the starting and ending point of the array and follow the steps given below: 

  • Stop if we have reached the end of the array
  • Increment the end index if start has become greater than end
  • Print the subarray from index start to end and increment the starting index

Below is the implementation of the above approach.  

C++




// C++ code to print all possible subarrays for given array
// using recursion
 
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to print all possible subarrays for
// given array
void printSubArrays(vector<int> arr, int start, int end)
{
    // Stop if we have reached the end of the array
    if (end == arr.size())
        return;
    // Increment the end point and start from 0
    else if (start > end)
        printSubArrays(arr, 0, end + 1);
    // Print the subarray and increment the starting point
    else {
        cout << "[";
        for (int i = start; i < end; i++)
            cout << arr[i] << ", ";
        cout << arr[end] << "]" << endl;
        printSubArrays(arr, start + 1, end);
    }
    return;
}
 
int main()
{
    vector<int> arr = { 1, 2, 3 };
    printSubArrays(arr, 0, 0);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


C




// C code to print all possible subarrays for given array
// using recursion
#include <stdio.h>
 
// Recursive function to print all possible subarrays for
// given array
void printSubArrays(int arr[], int start, int end, int size)
{
   
    // Stop if we have reached the end of the array
    if (end == size)
        return;
   
    // Increment the end point and start from 0
    else if (start > end)
        printSubArrays(arr, 0, end + 1, size);
   
    // Print the subarray and increment the starting point
    else {
        printf("[");
        for (int i = start; i < end; i++)
            printf("%d, ", arr[i]);
       
        // cout << arr[i] << ", ";
        printf("%d]\n", arr[end]);
       
        // cout << arr[end] << "]" << endl;
        printSubArrays(arr, start + 1, end, size);
    }
    return;
}
 
int main()
{
    int arr[] = { 1, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printSubArrays(arr, 0, 0, n);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


Java




// Java code to print all possible subarrays for given array
// using recursion
 
class solution {
 
    // Recursive function to print all possible subarrays
    // for given array
    static void printSubArrays(int[] arr, int start, int end)
    {
        // Stop if we have reached the end of the array
        if (end == arr.length)
            return;
        // Increment the end point and start from 0
        else if (start > end)
            printSubArrays(arr, 0, end + 1);
        // Print the subarray and increment the starting
        // point
        else {
            System.out.print("[");
            for (int i = start; i < end; i++)
                System.out.print(arr[i] + ", ");
            System.out.println(arr[end] + "]");
            printSubArrays(arr, start + 1, end);
        }
        return;
    }
 
    public static void main(String args[])
    {
        int[] arr = { 1, 2, 3 };
        printSubArrays(arr, 0, 0);
    }
}
 
// This code is contributed by Sania Kumari Gupta


Python3




# Python3 code to print all possible subarrays
# for given array using recursion
 
# Recursive function to print all possible subarrays
# for given array
def printSubArrays(arr, start, end):
     
    # Stop if we have reached the end of the array   
    if end == len(arr):
        return
     
    # Increment the end point and start from 0
    elif start > end:
        return printSubArrays(arr, 0, end + 1)
         
    # Print the subarray and increment the starting
    # point
    else:
        print(arr[start:end + 1])
        return printSubArrays(arr, start + 1, end)
         
# Driver code
arr = [1, 2, 3]
printSubArrays(arr, 0, 0)


C#




// C# code to print all possible subarrays
// for given array using recursion
using System;
 
class GFG
{
 
    // Recursive function to print all 
    // possible subarrays for given array
    static void printSubArrays(int []arr,
                        int start, int end)
    {
        // Stop if we have reached
        // the end of the array
        if (end == arr.Length)
            return;
 
        // Increment the end point
        // and start from 0
        else if (start > end)
            printSubArrays(arr, 0, end + 1);
 
        // Print the subarray and
        // increment the starting point
        else
        {
            Console.Write("[");
            for (int i = start; i < end; i++)
            {
                Console.Write(arr[i]+", ");
            }
 
            Console.WriteLine(arr[end]+"]");
            printSubArrays(arr, start + 1, end);
        }
        return;
    }
 
    // Driver code
    public static void Main(String []args)
    {
        int []arr = {1, 2, 3};
        printSubArrays(arr, 0, 0);
    }
}
 
// This code is contributed by Rajput-Ji


PHP




<?php
// PHP code to print all possible
// subarrays for given array using recursion
 
// Recursive function to print all
// possible subarrays for given array
function printSubArrays($arr, $start, $end)
{
    // Stop if we have reached
    // the end of the array
    if ($end == count($arr))
        return;
     
    // Increment the end point
    // and start from 0
    else if ($start > $end)
        return printSubArrays($arr, 0,
                              $end + 1);
         
    // Print the subarray and increment
    // the starting point
    else
    {
    echo "[";
    for($i = $start; $i < $end + 1; $i++)
    {
        echo $arr[$i];
        if($i != $end)
        echo ", ";
    }
    echo "]\n";
        return printSubArrays($arr, $start + 1,
                                    $end);
    }
}
 
// Driver code
$arr = array(1, 2, 3);
printSubArrays($arr, 0, 0);
 
// This code is contributed by mits
?>


Javascript




<script>
 
// Javascript code to print all possible
// subarrays for given array using recursion
 
// Recursive function to print all
// possible subarrays for given array
function printSubArrays(arr, start, end)
{
     
    // Stop if we have reached the end
    // of the array    
    if (end == arr.length)
        return;
       
    // Increment the end point and start
    // from 0
    else if (start > end)
        printSubArrays(arr, 0, end + 1);
           
    // Print the subarray and increment
    // the starting point
    else
    {
        document.write("[");
        for(var i = start; i < end; i++)
        {
            document.write( arr[i] + ", ");
        }
         
        document.write(arr[end] + "]<br>");
        printSubArrays(arr, start + 1, end);
    }
    return;
}
 
// Driver code
var arr = [ 1, 2, 3 ];
printSubArrays(arr, 0, 0);
 
// This code is contributed by rutvik_56
 
</script>


Output: 

[1]
[1, 2]
[2]
[1, 2, 3]
[2, 3]
[3]

 

Time Complexity: O(2n)

Auxiliary Space: O(2n)



Previous Article
Next Article

Similar Reads

Generating all possible Subsequences using Recursion including the empty one.
Given an array. The task is to generate and print all of the possible subsequences of the given array using recursion. Examples: Input : [1, 2, 3] Output : [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3], [] Input : [1, 2] Output : [2], [1], [1, 2], [] Approach: For every element in the array, there are two choices, either to include it in the sub
5 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Generating Random id's using UUID in Python
We had discussed the ways to generate unique id's in Python without using any python inbuilt library in Generating random Id’s in Python In this article we would be using inbuilt functions to generate them. UUID, Universal Unique Identifier, is a python library which helps in generating random objects of 128 bits as ids. It provides the uniqueness
3 min read
Pandas - Generating ranges of timestamps using Python
A timestamp is a string of characters or encrypted or encoded data that identifies the time and date of an event, usually indicating the time and date of day, and is often accurate to a fraction of a second. timestamps are used to maintain track of information. When information was created, transmitted, edited, or removed, it was given a timestamp.
3 min read
Generating Beautiful Code Snippets using Python
When creating technical documentation or tutorials, it can be helpful to include images of code snippets to illustrate specific examples or concepts. However, taking a screenshot of a code file can look unprofessional and hard to read. This article will explore how to convert programming code into beautiful image snippets in Python using the librar
3 min read
Generating Strong Password using Python
Having a weak password is not good for a system that demands high confidentiality and security of user credentials. It turns out that people find it difficult to make up a strong password that is strong enough to prevent unauthorized users from memorizing it. This article uses a mixture of numbers, alphabets, and other symbols found on the computer
3 min read
Reading and Generating QR codes in Python using QRtools
This article aims to introduce the use of the python library: qrtools. This library can be used to both read QR codes and generate them. What are QR codes? QR code, or quick response code, is a trademark for a type of 2 dimensional barcode. 2 dimensional barcodes are similar to one dimensional barcodes, but can store more information per unit area.
5 min read
Generating hash id's using uuid3() and uuid5() in Python
Python's UUID class defines four functions and each generates different version of UUIDs. Let's see how to generate UUID based on MD5 and SHA-1 hash using uuid3() and uuid5() .Cryptographic hashes can be used to generate different ID's taking NAMESPACE identifier and a string as input. The functions that support cryptographic hash generation are :
2 min read
Generating all divisors of a number using its prime factorization
Given an integer N, the task is to find all of its divisors using its prime factorization. Examples: Input: N = 6 Output: 1 2 3 6 Input: N = 10 Output: 1 2 5 10 Approach: As every number greater than 1 can be represented in its prime factorization as p1a1*p2a2*......*pkak, where pi is a prime number, k ? 1 and ai is a positive integer. Now all the
7 min read
Differences between number of increasing subarrays and decreasing subarrays in k sized windows
Given an array of integers and k, find the difference between the number of the strictly increasing number of subarrays (of size more than one) and the number of the strictly decreasing subarray in the window of size k. Examples: Input : nums = {10, 20, 30, 15, 15}; k = 3; Output : 3, 0, -1 Explanation For the first window of [10, 20, 30], there ar
8 min read
Split array into K subarrays such that sum of maximum of all subarrays is maximized
Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print "-1". Examples: Input: arr[] = {5, 3, 2, 7, 6, 4},
11 min read
Split given Array in minimum number of subarrays such that rearranging the order of subarrays sorts the array
Given an array arr[] consisting of N integers, the task is to find the minimum number of splitting of array elements into subarrays such that rearranging the order of subarrays sorts the given array. Examples: Input: arr[] = {6, 3, 4, 2, 1}Output: 4Explanation:The given array can be divided into 4 subarrays as {6}, {3, 4}, {2}, {1} and these subarr
7 min read
Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays
Given an array arr[] consisting of N integers, the task is to maximize the sum of the difference of the maximum and minimum in each subarrays by splitting the given array into non-overlapping subarrays. Examples: Input: arr[] = {8, 1, 7, 9, 2}Output: 14Explanation:Split the given array arr[] as {8, 1}, {7, 9, 2}. Now, the sum of the difference maxi
7 min read
Check if Array can be split into subarrays such that XOR of length of Longest Decreasing Subsequences of those subarrays is 0
Given an array of integers arr[] of size N, the task is to check whether arr[] can be split into different subarrays such that on taking the XOR of lengths of LDS (Longest decreasing subsequences) of all the subarrays is equal to 0. Print 'YES' if it is possible to split else print 'NO'. Examples: Input: arr[] = {1, 0, 3, 4, 5}Output: YESExplanatio
6 min read
Split into K subarrays to minimize the maximum sum of all subarrays
Given an Array[] of N elements and a number K. ( 1 &lt;= K &lt;= N ) . Split the given array into K subarrays (they must cover all the elements). The maximum subarray sum achievable out of K subarrays formed, must be the minimum possible. Find that possible subarray sum.Examples: Input : Array[] = {1, 2, 3, 4}, K = 3 Output : 4 Optimal Split is {1,
15 min read
Generating random Id's in Python
In python there are different ways to generate id's. Let's see how different types of Id's can be generated using python without using inbuilt Python libraries. 1. Generating Random Integer as Ids' Code #1 : Print 10 random values of numbers between 1 and 100. C/C++ Code # Python3 code to demonstrate the # random generation of Integer id's import r
2 min read
Generating Word Cloud in Python
Word Cloud is a data visualization technique used for representing text data in which the size of each word indicates its frequency or importance. Significant textual data points can be highlighted using a word cloud. Word clouds are widely used for analyzing data from social network websites. For generating word cloud in Python, modules needed are
2 min read
Mathematics | Generating Functions - Set 2
Prerequisite - Generating Functions-Introduction and Prerequisites In Set 1 we came to know basics about Generating Functions. Now we will discuss more details on Generating Functions and its applications. Exponential Generating Functions - Let [Tex]h_0, h_1, h_2, ........., h_n, ...... [/Tex]e a sequence. Then its exponential generating function,
3 min read
Generating Word Cloud in Python | Set 2
Prerequisite: Generating Word Cloud in Python | Set - 1Word Cloud is a data visualization technique used for representing text data in which the size of each word indicates its frequency or importance. Significant textual data points can be highlighted using a word cloud. Word clouds are widely used for analyzing data from social network websites.F
5 min read
Generating numbers that are divisor of their right-rotations
Given a number m, find all numbers which have m digits and are a divisor of their right rotation. Right-rotation of a number N is the result of rotating the digits of N one place to the right and wrapping the least significant digit around so that it becomes the most significant digit. For example, the right-rotation of 4356 is 6435. Examples: Inpu
10 min read
Subset array sum by generating all the subsets
Given an array of size N and a sum, the task is to check whether some array elements can be added to sum to N . Note: At least one element should be included to form the sum.(i.e. sum cant be zero) Examples: Input: array = -1, 2, 4, 121, N = 5 Output: YES The array elements 2, 4, -1 can be added to sum to N Input: array = 1, 3, 7, 121, N = 5 Output
5 min read
Generating Lyndon words of length n
Given an integer n and an array of characters S, the task is to generate Lyndon words of length n having characters from S. A Lyndon word is a string which is strictly less than all of its rotations in lexicographic order. For example, the string "012" is a Lyndon word as it is less than its rotations "120" and "201", but "102" is not a Lyndon word
6 min read
Generating N-bit Grey Code starting from K
Given a value N and K, the task is to generate N-bits Gray Code starting from the value K.Examples: Input: N = 2, K = 3 Output: 3 2 0 1 Explanation: 3 -&gt; 11 2 -&gt; 10 0 -&gt; 00 1 -&gt; 01 Each value differ by only one bit from the next value in their binary representation.Input: N = 3, K = 2 Output: 2 3 1 0 4 5 7 6 Approach: Gray code are numb
4 min read
Linear Congruence method for generating Pseudo Random Numbers
Linear Congruential Method is a class of Pseudo Random Number Generator (PRNG) algorithms used for generating sequences of random-like numbers in a specific range. This method can be defined as: [Tex]X_{i + 1} = aX_{i} + c \hspace{0.2cm} mod \hspace{0.2cm} m [/Tex] where, X, is the sequence of pseudo-random numbersm, ( &gt; 0) the modulusa, (0, m)
6 min read
Multiplicative Congruence method for generating Pseudo Random Numbers
Multiplicative Congruential Method (Lehmer Method) is a type of linear congruential generator for generating pseudorandom numbers in a specific range. This method can be defined as: [Tex]\[X_{i + 1} = aX_{i} \hspace{0.2cm} mod \hspace{0.2cm} m\] [/Tex] where, X, the sequence of pseudo-random numbersm ( &gt; 0), the modulusa (0, m), the multiplierX0
6 min read
Pafy - Generating File Name of Stream
In this article we will see how we can generate file name of given youtube video stream in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Stream is basically available resolution of video is available on youtube. File name is the t
2 min read
Generating Basic Discrete Time Signals
Generating basic discrete-time signals for Discrete-Time Signal ProcessingUnit Step, Unit Impulse, Unit Ramp, exponential signals are very commonly used signals in signal processing to perform various operations. Unit step signal is given byUnit impulse signal is given byUnit ramp signal is given byExponential signal is given by Examples: Input : U
2 min read
Distinct Numbers obtained by generating all permutations of a Binary String
Given a binary string S, the task is to print all distinct decimal numbers that can be obtained by generating all permutations of the binary string. Examples: Input: S = "110"Output: {3, 5, 6}Explanation: All possible permutations are {"110", "101", "110", "101", "011", "011"}.Equivalent decimal numbers of these binary strings are {6, 5, 6, 5, 3, 3
8 min read
Generating dynamic URLs in Flask
Prerequisites: Basics of Flask When creating an application, it's quite cumbersome to hard-code each URL. A better way to resolve this problem is through building Dynamic URLs. Let us briefly understand the meaning of a few common terms first. Dynamic Routing: It is the process of getting dynamic data(variable names) in the URL and then using it.Va
3 min read
Maximum median possible by generating an Array of size N with sum X
Given two positive integers N and X. The task is to print the maximum median possible by generating an Array of size N with sum X Examples: Input: N = 1, X = 7Output: 7Explanation: Array can be: [7], median is the 1st element, i.e., 7. Input: N = 7, X = 18Output: 4Explanation: One of the possible arrays can be: [0, 1, 2, 3, 4, 4, 4]. The median = c
4 min read
three90RightbarBannerImg