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

Generating subarrays using recursion

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

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
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
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
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
three90RightbarBannerImg