Time complexity refers to the time needed for your program or algorithm to execute. Some programs execute faster than others, even if the end goal is the same. There are various factors involved in this time difference. For example:
Although some factors are hard to improve, we can certainly improve our algorithm so that it takes less time to execute.
We determine time complexity by counting the number of the elementary operations that an algorithm takes in terms of the size of the input. First, let’s take a look at the following points:
Time of an algorithm is measured as a function of input size.
Time of an algorithm is measured in terms of the number of steps or primitive operations performed.
Consider the following sum algorithm for an array:
int sum(int arr[], int n){int s = 0;for(int i = 0; i < n; i++){s = s + arr[i];}return s;}
The following steps or primitive operations were performed in this algorithm.
s
and initialize it with 0.i
and initialize it with 0. This variable is used as a counter in our for
loop.i
and n
. This comparison serves as a break condition for our loop.i
by one 1 value.=
operator to the variable s
.s
variable and value of the array at the index equal to the value of variable i
.i
th index.s
to the main function.Now, you may notice that steps 1, 2, and 8 are only executed once, irrespective of the size of the input array.
However, steps 3, 4, 5, 6, and 7 depend upon the input array’s size. For example, if there is an input array of size 5, we will execute the above steps 5 times. Thus, the number of times that these steps are executed is directly proportional to the size of the input array.
In the end, we have 3 steps that are executed once, and we have 5 steps that are executed n
times. The overall time complexity of the algorithm is summarized below.
f(n) = 5n + 3
Free Resources