I was trying to find the complexities of an algorithm via different approaches. Mathematically I came across one O(m+n) and another O(mn) approach. However I am unable to gr
O(m+n)
example:
for(int i = 0, i < m, i++)
//code
for(int j = 0, j < n, j++)
//code
m
iterations of code happen. Then n
iterations of code happens.
O(mn)
example:
for(int i = 0, i < m, i++)
for(int j = 0, j < n, j++)
//code
For every iteration of m
, we have n
iterations of code. Imagine iterating over a non-square 2D array.
m
and n
do not necessarily equal the same value. If they did equal the same value, then for O(m+n)
:
O(m+n) => O(m+m) => O(2m) => O(m)
I'd recommend looking at this question/answer in order to understand that last transition.
And for O(mn)
:
O(mn) => O(mm) => O(m^2)