I am new to Algorithms, and very much interested in learning and implementing them.
Learning them through all available online materials i can find.
I am a little confused regarding this -
Consider this code -
for (int i=0; i<n; i++) { ..... }
for (int i=0; i<n; i++) { ..... }
What will be the complexity of this ?
O(n) or O(n^2) ?
Assuming that the { . . . }
is constant time, then the complexity of one loop is O(n).
What is the complexity of two "adjacent" loops? It is O(n) + O(n). Or you could think of this as O(n + n) --> O(2n). Constants drop out of complexity, so this is O(n).
It is an entirely different matter with nested loops. So the following:
for (int i=0; i<n; i++) { ..... }
for (int j=0; j<n; j++) { ..... }
would be O(n^2).
The complexity will remain O(n)
(Assuming that you don't have another loop inside those for loops).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With