Is O(mn) better than O((m+n)^2)?

Viewed 170

The inputs to the algorithm are m and n.

The time complexity of my algorithm comes out to be O(mn).

I have a benchmark algorithm that has a time complexity of O((m+n)²).

Is my implementation better than the benchmark in terms of time complexity?

3 Answers

So many commenters and answerers wish to consider only the case when m = n or at least when they are related by a constant factor. That is not how this works.

Your algorithm is clearly faster when we hold either m or n constant; for example, if we restrict ourselves to the case m = 1 then the complexity of your algorithm is O(n) whereas the alternative is O(n^2), so yours is clearly better in this restricted case.

What we can say is that (m+n)^2 = m^2 + n^2 + 2mn is clearly Ω(mn) where Ω means this is a lower bound, and your algorithm is (asymptotically) always at least as good; i.e. there are no restricted cases where the other algorithm is asymptotically better than yours. But we do know there are restricted cases where yours is better. So, overall, yours is better.

Yes, your implementation is better. Recall that (m+n)^2 = m^2 + n^2 + 2mn, so (m+n)^2 > mn

O(mn) is not in all cases better than O((m+n)²).


Look at this case:

O((m+n)²) = O(mn) if m=O(n)

for m=O(n) be can introduce a new variable (c:= max(n,m))

O((m+n)²) = O(m² + 2mn + n²) 
           = O(c² + 2cc + c²=
           = O( 3* c²)
           = O(c²)

O(mn)      = O(cc) = O(c²)

So in the case that n and m only differ by about a constant both complexities are the same.


As mentioned in the comments if not m=O(n)
than O(mn) is better iff O(n²) > O(nm) or O(m²) > O(mn).


My Fazit: Depending on your definition of "better", you can say:
O(mn) is never worse than O((m+n)²)
or
O(mn) is better than O((m+n)²)

Related