How to find all possible subarrays of an array? [closed]
We can use substr function to find the all possible sub array.
Code Snippet :
#include<bits/stdc++.h>
using namespace std;
void generateSubstring(string str)
{
if(str.size()==0)
{
return;
}
else
{
for(int i=0; i<str.size(); i++)
{
for(int j=1; j<=str.size()-i; j++)
{
cout<<str.substr(i, i+j)<<endl;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
string str;
getline(cin, str);
generateSubstring(str);
return 0;
}
Subarray of an array A is A[i..j]
where 0 <= i <= j < n
where n is length of array.
In C language it can be calculated like this:
#include <stdio.h>
int main(){
int A[] = {1,2,3,4,5};
int len=sizeof(A)/sizeof(int);
for( int i=0; i<len; i++ ){
for( int j=i; j<len; j++ ){ // Now A[i..j] is the subarray
for( int k=i; k<=j; k++ )
printf("%d ", A[k]);
printf("\n");
}
}
return 0;
}
A O(n^2) approach could be:
for (int i = 0; i < arr.length; i++) {
String res = "";
for (int j = i; j < arr.length; j++) {
res += arr[j] + " ";
System.out.println(res);
}
}