Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any O(n^2) algorithm to generate all sub-sequences of an array?

I was wondering if there is any O(n^2) complexity algorithm for generating all sub-sequences of an array. I know an algorithm but it takes O((2^n)*n) time.

int main() {
    int n; 
    cin >> n;
    vector<int> a(n);
    for(int i = 0; i < n; ++i) 
        cin >> a[i];
    int64_t opsize = pow(2,n);
    for (int counter = 1; counter < opsize; counter++) {
        for (int j = 0; j < n; j++) {
           if (counter & (1 << j))
                 cout << a[j] << " ";
        }
        cout << endl;
    }
}
like image 283
Naimish Singh Avatar asked Jul 06 '18 15:07

Naimish Singh


2 Answers

No

There cannot be any algorithm of less than O(2^n) complexity simply because there are O(2^n) sub-sequences. You need to print each of them hence the time complexity has to be greater than or equal to O(2^n).

like image 103
random40154443 Avatar answered Oct 18 '22 21:10

random40154443


You can't improve algorithm complexity, but you can improve how stream is used. As other answer points out o(n * 2^n) is best you can have.

When you use std::endl you are flushing buffers of streams. To achieve best performance buffers should flush them selves when they are full. Since each subsequence have to be quite short (at maximum 64 elements), it means that you are flushing stream quite often and have serious performance hit. So replacing std::endl with '\n' will provide significant performance improvement.

Other tricks which can help improve stream performance:

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int n; 
    cin >> n;
like image 24
Marek R Avatar answered Oct 18 '22 21:10

Marek R