Generating All Subarrays (original) (raw)
Last Updated : 07 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 C++ `
#include #include using namespace std;
// Prints all subarrays in arr[0..n-1] void subArray(vector &arr) { int n = arr.size();
// Pick starting point
for (int i = 0; i < n; i++)
{
// Pick ending poin
for (int j = i; j < n; j++)
{
// Print subarray between current starting
// and ending points
for (int k = i; k <= j; k++)
cout << arr[k] << " ";
cout << endl;
}
}
}
int main() { vector arr = {1, 2, 3, 4}; cout << "All Non-empty Subarrays\n"; subArray(arr); return 0; }
C
#include <stdio.h>
//Prints all subarrays in arr[0..n-1] void subArray(int arr[], int n) {
// Pick starting point
for (int i = 0; i < n; i++) {
// Pick ending point
for (int j = i; j < n; j++) {
// Print subarray between current starting and ending points
for (int k = i; k <= j; k++) {
printf("%d ", arr[k]);
}
printf("\n");
}
}
}
int main() { int arr[] = {1, 2, 3, 4}; int n = sizeof(arr) / sizeof(arr[0]); printf("All Non-empty Subarrays:\n"); subArray(arr, n); return 0; }
Java
import java.util.ArrayList;
public class GfG {
//Prints all subarrays in arr[0..n-1]
static void subArray(ArrayList<Integer> arr) {
int n = arr.size();
// Pick starting point
for (int i = 0; i < n; i++) {
// Pick ending point
for (int j = i; j < n; j++) {
// Print subarray between current starting and ending points
for (int k = i; k <= j; k++) {
System.out.print(arr.get(k) + " ");
}
System.out.println();
}
}
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
System.out.println("All Non-empty Subarrays:");
subArray(arr);
}
}
Python
#Prints all subarrays in arr[0..n-1] def sub_array(arr): n = len(arr)
# Pick starting point
for i in range(n):
# Pick ending point
for j in range(i, n):
# Print subarray between current starting and ending points
for k in range(i, j + 1):
print(arr[k], end=" ")
print() # New line after each subarray
Driver code
arr = [1, 2, 3, 4] print("All Non-empty Subarrays:") sub_array(arr)
C#
using System; using System.Collections.Generic;
class GfG {
//Prints all subarrays in arr[0..n-1]
static void SubArray(List<int> arr) {
int n = arr.Count;
// Pick starting point
for (int i = 0; i < n; i++) {
// Pick ending point
for (int j = i; j < n; j++) {
// Print subarray between current starting and ending points
for (int k = i; k <= j; k++) {
Console.Write(arr[k] + " ");
}
Console.WriteLine();
}
}
}
static void Main() {
List<int> arr = new List<int> { 1, 2, 3, 4 };
Console.WriteLine("All Non-empty Subarrays:");
SubArray(arr);
}
}
JavaScript
//Prints all subarrays in arr[0..n-1] function subArray(arr) { const n = arr.length;
// Pick starting point
for (let i = 0; i < n; i++) {
// Pick ending point
for (let j = i; j < n; j++) {
// Print subarray between current starting and ending points
let subarr = [];
for (let k = i; k <= j; k++) {
subarr.push(arr[k]);
}
console.log(subarr.join(" "));
}
}
}
const arr = [1, 2, 3, 4]; console.log("All Non-empty Subarrays:"); subArray(arr);
`
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.
C++ `
// C++ code to print all possible subarrays for given array // using recursion #include #include using namespace std;
// Recursive function to print all possible subarrays for given array void printSubArrays(vector& 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 reset the start to 0
else if (start > end)
printSubArrays(arr, 0, end + 1);
// Print the subarray and increment the starting point
else {
for (int i = start; i <= end; i++)
cout << arr[i] << " ";
cout << endl;
printSubArrays(arr, start + 1, end);
}
}
int main() { vector arr = {1, 2, 3}; printSubArrays(arr, 0, 0); return 0; }
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]);
printf("%d]\n", arr[end]);
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; }
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);
}
}
Python
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);
}
}
JavaScript
// 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) {
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 {
let subArray = "[";
for (var i = start; i < end; i++) {
subArray += arr[i] + ", ";
}
subArray += arr[end] + "]";
console.log(subArray);
printSubArrays(arr, start + 1, end);
}
return;
}
var arr = [1, 2, 3]; printSubArrays(arr, 0, 0);
`
Output
1 1 2 2 1 2 3 2 3 3
Similar Reads
- Array Data Structure Complete Guide to ArraysLearn more about Array in DSA Self Paced CoursePractice Problems on ArraysTop Quizzes on Arrays What is Array?An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calcul 3 min read
- What is Array? Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of same data type stored at contiguous memory locations. For simplicity, we can think of an array as a flight of stairs where on each step is placed a value (let's say one of your friends). 2 min read
- Getting Started with Array Data Structure Array is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr 14 min read
- Applications, Advantages and Disadvantages of Array Array is a linear data structure that is a collection of data elements of same types. Arrays are stored in contiguous memory locations. It is a static data structure with a fixed size.Table of ContentApplications of Array Data Structure:Advantages of Array Data Structure:Disadvantages of Array Data 2 min read
- Subarrays, Subsequences, and Subsets in Array What is a Subarray?A subarray is a contiguous part of array, i.e., Subarray is an array that is inside another array. In general, for an array of size n, there are n*(n+1)/2 non-empty subarrays. For example, Consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are: (1), 10 min read