Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Find the all possible subarrays of an array efficiently? [closed]

Let's suppose I am given an array; A[] = {1,2,3} and I want to find all the sub-arrays of this array. The answer should be

{1}
{1,2}
{1,2,3}
{2}
{2,3}
{3}

How to find all possible subarrays of an array efficiently?

like image 344
rashedcs Avatar asked Dec 05 '16 10:12

rashedcs


2 Answers

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;
}
like image 175
Ankit Vallecha Avatar answered Oct 02 '22 08:10

Ankit Vallecha


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;
        }
like image 25
rashedcs Avatar answered Oct 02 '22 08:10

rashedcs