Skip to main content

Command Palette

Search for a command to run...

Time Complexity Examples with Codes

Published
•1 min read•View as Markdown

1) printf("Hello World")

The time complextiy for above will be O(1) since it will run in constant time throughout the number of iterations therefore it is called as constant time.

2) int val = 0;

for(int i = 1; i <= N; i += i){

val++;

}

We will calculate the total number of iterations in the above loop to calculate the time complexity. Total number of iterations will be:

1, 2, 4, 8, 16, ... 2k <= N

k ~ logN

Hence, the time complextiy for the above code will be O(logn).

in the above code you can see we need to find the key in array by traversing it so we will traverse the whole array so its time complexity would be O(n) its good time complexity still we can optimize it in order to reduce the time complexity lets see the optimized solution :

this is the optimized solution having time complextiy O(log(n)) so this is what optimization means its all about binary search you can learn by click on it through by blog.

That's all for Time Complexity comment on next topic till then HAPPY READING!!!! Don't forget to follow me on instagram and linkedin.