Search code examples
performancealgorithmsortingcomplexity-theorytime-complexity

Time Complexity - Calculating Worst Case For Algorithms


I am reading some information on time complexity and I'm quite confused as to how the following time complexities are achieved and if there is a particular set of rules or methods for working this out?

1)

Input: int n
for(int i = 0; i < n; i++){
   print("Hello World, ");
}
for(int j = n; j > 0; j--){
   print("Hello World");
}
  • Tight: 6n + 5
  • Big O: O(n)

2)

Input: l = array of comparable items
Output: l = array of sorted items
Sort:
for(int i = 0; i < l.length; i++){
     for(int j = 0; j < l.length; j++){
         if(l{i} > l{j}){
} }
     Swap(l{i},l{j});
}
return ls;
  • Worst Case Time Complexity: 4n2 +3n+2 = O(n2)

Solution

  • In the first example, the array has n elements, and you go through these elements Twice. The first time you start from index 0 until i, and the second time you start from index n to 0. So, to simplify this, we can say that it took you 2n. When dealing with Big O notation, you should keep in mind that we care about the bounds:

    As a result, O(2n)=O(n) and O(an+b)=O(n)

    Input: int n                        // operation 1
        for(int i = 0; i < n; i++){    // operation 2
        print("Hello World, ");       // Operation 3 
       }
    for(int j = n; j > 0; j--)       // Operation 4
       {
       print("Hello World");        //Operation 5
        }             
    

    As you can see, we have a total of 5 operations outside the loops.

    Inside the first loop, we do three internal operations: checking if i is less than n, printing "Hello World", and incrementing i .

    Inside the second loop, we also have three internal operations.

    So, the total number of of opetations that we need is: 3n ( for first loop) + 3n ( second loop) + 5 ( operations outside the loop). As a result, the total number of steps required is 6n+5 ( that is your tight bound).

    As I mentioned before, O( an +b )= n because once an algorithm is linear, a and b do not have a great impact when n is very large.

    So, your time complexity will become : O(6n+5) =O(n).

    You can use the same logic for the second example keeping in mind that two nested loops take n² instead of n.