VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generating-subarrays-using-recursion/

⇱ Generating All Subarrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generating All Subarrays

Last Updated : 7 Feb, 2025

Given an array arr[], the task is to generate all the possible subarrays of the given array.

Examples:

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

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

Iterative Approach

To generate a subarray, we need a starting index from the original array. For choosing the starting index, we can run a loop from [0 to n-1] and consider each i as the starting index. For each starting index i, we can select an ending index from the range [i to n-1]. A nested loop from [i to n-1] will help in selecting the ending index. Once we have the starting and ending indices, we need an innermost loop to print the elements in this subarray.

  • Outermost Loop: Picks starting index of current subarray
  • Middle Loop: Picks ending index of current subarray
  • Innermost Loop: Prints the subarray from the starting index to the ending index

Output
All Non-empty Subarrays
1 
1 2 
1 2 3 
1 2 3 4 
2 
2 3 
2 3 4 
3 
3 4 
4 

Recursive 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.  


Output
1 
1 2 
2 
1 2 3 
2 3 
3 


Comment
Article Tags: