Examples Related to Time Complexities
Explore detailed examples of time complexity to understand how different code structures like loops and nested loops impact algorithm efficiency. Learn to analyze complexities such as linear, quadratic, logarithmic, and more, to improve your skills in optimizing Go programs.
We'll cover the following...
- Example 1: for loop
- Example 2: Nested for loop
- Example 3: Arithmetic series
- Example 4: Double the iteration variable
- Example 5: Half the iteration variable
- Example 6: Square root iteration
- Example 7: Nested loop in O(n)
- Example 8: Arithmetic progression
- Example 9: Triple nested loop
- Example 10: Multiple loops in O(n)
Let’s better understand the time complexity by going through a few examples.
Example 1: for loop
The case below is a for loop. We have a time complexity of .
The statement on line 10 takes constant time. Hence, it doesn’t affect the time complexity of the loop.
Example 2: Nested for loop
In this case, we have a nested loop where the total number of loops is 2. Both loops run n times. According to formula , its time complexity is .
Example 3: Arithmetic series
This example shows that the inner loop iterates times, and the outer loop iterates times.
The exact number of steps will go the same way as those of the arithmetic series. In this case, the time complexity will be: = ...