Difference between O(m+n) and O(mn)?

后端 未结 3 1288
梦如初夏
梦如初夏 2020-12-30 15:47

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

3条回答
  •  情话喂你
    2020-12-30 16:28

    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)
    

提交回复
热议问题