Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the complexity of running a loop twice of the same input array?

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) ?

like image 520
Ashish Gogna Avatar asked Sep 21 '25 01:09

Ashish Gogna


2 Answers

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).

like image 194
Gordon Linoff Avatar answered Sep 22 '25 14:09

Gordon Linoff


The complexity will remain O(n)

(Assuming that you don't have another loop inside those for loops).

like image 35
Vatsal Prakash Avatar answered Sep 22 '25 15:09

Vatsal Prakash