Skip to content
Advertisement

How to justify the time complexity of an algorithm?

I’m relatively new to data structures and could use a bit of help on how you approach justifying an algorithm. I believe the algorithm below to be the time complexity of O(n + m) because you iterate through two different arrays independently. You can also assume the arrays are always sorted.

public static void intersectionTwoArrays(int[] a, int[] b){
    
        int i = 0;// Index for array a
        int j = 0;// Index for array b
    
        //
        while(i < a.length && j < b.length){
        
            if(a[i] == b[j]){
                System.out.println(a[i]);
                i++;
                j++;
            }
            
            else if(a[i] < b[j]){
                i++;
            }
        
            else if(a[i] > b[j]){
                j++;
            }
            
        }// end while
    
    }// end Method
    
    public static void main(String[] args){
    
        int[] list1 = {0,1,3,5,6,8,10,11};
        int[] list2 = {0,2,3,4,7,8,11};
        
        intersectionTwoArrays(list1, list2);
        
    }// end main

Advertisement

Answer

Yep, the time complexity is O(n + m).

The worst case scenario could be such that a consists of consecutive odd integers and b – of consecutive even integers (positive) as below:

a = 1 3 5 ... 2k+1
b = 2 4 6 ... 2k+2

In this case, both i and j will be incremented up to a.length and b.length. That is exactly a.length + b.length steps or O(n + m), where n = a.length and m = b.length

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement