Types of Time complexities
Lesson 8 of 26 in Coddy's Arrays in C++ course.
The types of time complexities depend upon the number of times a line of code has to iterate. We always look for the worst time complexity which is called O(x) where x denotes the time complexity and O is called big O.
O(1)
This is called the constant time. it means in any condition these type of programs does not depend upon the value of the variables and the type of variable that a program has.
Example
cout<<"Hello World!!!"<<endl;This code does not depend on any kind of variable and therefore this single line of code will be executed in constant time. hence it has a time complexity of O(1).
O(n)
This is called linear time. if a code is taking n iterations then it belongs to O(n) time complexity.
For example
For(int i=0;i<n;i++){
cout<<"Hello World!!!"<<endl;
}in this program "Hello World!!!" is printed n times which means this loop will be it will be iterated n times. that makes its time complexity O(n).
O(n2)
This time complexity arises generally when we use nested loops.
For example
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<j<<endl;
}
}In this program, the outer loop runs n times, and every time the outer loop runs the inner loop also runs n times, therefore there is a total of n iterations n times. therefore makes the time complexity of O(n2)
In such a manner O(n*log n), O(log n), O(2n), and all such time complexities exist. We optimize the code in such a way that it should take minimum time to execute the program.
Try it yourself
This lesson doesn't include a code challenge.