Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I right in thinking this snippet is O(n^3)?

Tags:

c#

big-o

collection.Where(i => i.condition)
.ToList()
.ForEach(i => SomeComplicatedOpInvolving_i);

I'm not looking for answers telling me there is an easier way of doing this, just treat it as a thought experiment.

First up, am I right in thinking that this is three loops? Where(), ToList() and ForEach()?
Second of all, (assuming it is three loops) am I right in thinking this is n to the power of 3 in big O notation?

Thanks everyone.

like image 352
Adam Naylor Avatar asked Sep 01 '11 09:09

Adam Naylor


People also ask

Are all nested loops N 2?

To your other question, the answer is no. They aren't always O(n^2) . You can easily create a situation where one of the loops affects the iterations of the other, yielding a different complexity.

What is the time complexity of two non nested for loops?

It would be O(2n) because you run n+n = 2n iterations. O(2n) is essentially equivalent to O(n) as 2 is a constant.


2 Answers

No, actually. I think it should be O(n).

Where() runs in O(n) (assuming condition is constant)

ToList() runs over all the results of Where as well, so O(n) too

ForEach() runs over the entire list produced by ToList once, so also O(n). I assume SomeComplicatedOpInvolving_i doesn't scale with the number of i's...

The key point here is that the loops aren't nested, they run one after another - so total runtime is 3*O(n), which is the same as O(n).

like image 167
Peter Avatar answered Oct 28 '22 06:10

Peter


No, they are not nested loops. It is O(n).

Avoid using ToList(), that costs O(n) storage for no good reason. Check this blog post.

like image 27
Hans Passant Avatar answered Oct 28 '22 06:10

Hans Passant