Question

I've computed complexity of below algorithm as

for i = 0 to m
    for j = 0 to n
        //Process of O(1)

Complexity: O( m * n)

This is simple example of O( m * n). But I'm not able to figure out how O(m+n) computed. Any sample example

Was it helpful?

Solution 2

for i=0 to m
 //process of O(1)
for i=0 to n
 //process of O(1)

time complexity of this procedure is O(m+n).

OTHER TIPS

O(m+n) means O(max(m,n)). A code example:

for i = 0 to max(m,n)
    //Process

The time complexity of this example is linear to the maximum of m and n.

You often get O(m+n) complexity for graph algorithms. It is the complexity for example of a simple graph traversal such as BFS or DFS. Then n = |V| stands for the number of vertices, m = |E| for the number of edges, where the graph is G=(V,E).

The Knuth-Morris-Pratt string-searching algorithm is an example.

http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Efficiency_of_the_KMP_algorithm

The string you're looking for (the needle or the pattern) is length m and the text you're searching through is length n. There is preprocessing done on the pattern which is O(m) and then the search, with the preprocessed data, is O(n), giving O(m + n).

The above example you have is a nested for loop, when you have nested loops and have 2 different inputs m and n ( considered very large in size). The complexity is said to be multiplicative. so for first for loop you write complexity O(m) and for inner for loop you write O(n) and as they are nested loop, you can write as O (m) * O(n) or O(m * n).

static void AddtiviteComplexity(int[] arr1,int[] arr2)
{
    int i = 0;
    int j = 0;

    while (i < arr1.Length)
    {
        Console.WriteLine(arr1[i]);

        while (j < arr2.Length)
        {
            Console.WriteLine(arr2[j]);
            j++;
        }

        i++;
    }           
}

similarly when have 2 loops and they are not nested and have 2 different inputs m and n ( considered very large in size), the complexity is said to be additive. For the First loop, you write the complexity O(m) and for the second loop you write the complexity O(n) and as there are separate loops, you can write the complexity as O(m) + O(n) or O(m + n).

 static void AddtiviteComplexity(int[] arr1,int[] arr2)
    {
        int i = 0;
        int j = 0;

        while(i< arr1.Length)
        {
            Console.WriteLine(arr1[i]);
            i++;
        }

        while (j < arr2.Length)
        {
            Console.WriteLine(arr2[j]);
            j++;
        }
    }

Note: the above code is for example with int array is example purpose. Also I have used while loop, it doesn't matter if it's a while or a for loop for calculating complexity.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top