I have problem in determining time complexities of algorithms.
for(int i=0;i <n i++){} O(n)
for(int i= 0 ;i<n ;i++){ O(n^2)
for(int j=0;j<n;j++){
}
}
Now for following code whats the complexity
for(i =0; i<n ; i++) {}
for (j=0;j<n ;j++ ) {}
is it O(2n) as it invloves 2 seperate loops?
what if i start j =5 to n?
There is no
O(2n), it’s justO(n). In other words, it scales at the same rate asnincreases.If it was a nested loop, it would be
O(n2)but the presence of your{}empty blocks means it isn’t nested.And it makes no difference whether you start at one or five, it still scales with
n, just with a slightly negative constant addition. Hence stillO(n).The complexities
O(n),O(cn)andO(n+c)(wherecis a constant) are all equivalent. In addition, you also generally only use the term with the highest effect.So you won’t usually see
O(7n3 + 3n2 + 12n + 2), that will be simplified toO(n3).