Find all consecutive sequences in an ordered set I have the following set. a = [1,2,3,4,5] and i want to find all of the following sequences of consecutive elements:

1,
1,2
1,2,3
1,2,3,4
1,2,3,4,5
2,
2,3,
2,3,4,
2,3,4,5
3,
3,4
3,4,5
4
4,5
5


This is the following code that I use and works correctly. My only problem is with the complexity of the algorithm O(n2). Is there a better approach that I can use to reduce the complexity?

    int main()
    {
        int a[5] = {1,2,3,4,5};
           vector&lt;vector&lt;int&gt;&gt; all;
            for(int i = 0; i &lt; 5; i ++)
            {
                vector&lt;int&gt; g;
                g.push_back(a[i]);
                all.push_back(g);
               for(int j = i+1; j &lt; 5; j++)
               {
                    g.push_back(a[j]);
                    all.push_back(g);
               }
               g.clear();
            }

            for(int i = 0; i &lt; all.size();i++)
            {
               for(int j = 0; j &lt; all[i].size();j++)
               {
                    cout &lt;&lt; all[i][j] &lt;&lt; "  ";
               }
               cout &lt;&lt; endl;
            }

        return 0;
    }
You cannot get better than O(n²) because the result has the size of O(n²)

The Output has (n+1)*n/2 elements therefore you will always need O(n²) time to do the output.

You can only try to reduce the constant factor.