O(N+M) time complexity

后端 未结 3 1133
孤街浪徒
孤街浪徒 2021-02-12 09:52

I\'m working through some practice problems where I\'m given a target time complexity and space complexity. One of them gives a target time complexity of O(N+M). I\'m having som

相关标签:
3条回答
  • 2021-02-12 10:26

    Quick and simple example of an O(n + m) algorithm:

    for (i = 0; i < n; i++)
    {
      // do something but don't loop or invoke recursive functions
      // only constant O(c) complexity is allowed: a simple series of commands
    }
    
    for (i = 0; i < m; i++)
    {
      // idem
    }
    

    Complexity is commutative when added (O(n + m) == O(m + n)) this means you may invert the two for() without affecting complexity. Obviously, on an algorithmic level the inverted one MAY not be equivalent to the straight one.

    As an additional help, here is an example of O(n * m) algorithm:

    for (i = 0; i < n; i++)
    {
      for (j = 0; j < m; j++)
      {
        // do something but don't loop or invoke recursive functions
        // only constant O(c) complexity is allowed: a simple series of commands
      }
    }
    

    Again, you may invert inside with outside loop without affecting complexity (O(n * m) == O(m * n)). The same obvious considerations apply.

    The limitation on what you may put into the for() bodies is because the big-o notation constraints the upper bound. If it were a lower bound (little-o notation) you may have put more complex stuff in, but it could never get less than that.

    0 讨论(0)
  • 2021-02-12 10:33

    So, in order to expand the other replies, I will try to add a example of such problems to help you understand:

    • Find a min/max in a N sized array, and then look for this value in an M sized array. Since you need to perform first min/max search, you cannot do it at once.

    For instance, summing up the elements of 2 vectors can be done in O(M+N), but it can be thought as O(N) (assuming N>M) or O(M) (if M>N).

    0 讨论(0)
  • 2021-02-12 10:34

    A simple example of algorithm that is O(m+n):

    int sum(int[] nArr, int[] mArr) {
        int sum = 0;
        for(int i : nArr) {
            sum += i;
        }
        for(int i : mArr) {
            sum += i;
        }
        return sum;
    }
    

    To compute the sum, you need to go through all elements in nArr (size n) and all elements in mArr (size m), so the overall complexity is O(m+n)

    0 讨论(0)
提交回复
热议问题