L6-Time Complexity Analysis
L6-Time Complexity Analysis
ANALYSIS
EXAMPLES WITH SOLUTIONS
Problem statement
• Analyze and find the time complexity of the below
function from the code snippet.
for(int i=1;i<=n;i++){
cout<<i<<endl;
i++;
}
SOLUTION
• In the above code, the value of i will increase by 2 for each iteration of
the loop as once it will increment inside the body of the for loop and
once for conditional increment.
• So, the loop will run (n/2) times. Then, we can say the time
complexity of the above code is O(n/2) which is equivalent to O(n).
Problem statement
• Analyze and find the time complexity of the below
function from the code snippet.
for(int i=1;i<=n;i++){
cout<<i<<endl;
}
for(int j=1;j<=m;j++){
cout<<j<<endl;
}
SOLUTION
• In the above code, the first loop will run n times and the second loop
will run m times So, we can say the time complexity of the above code
is O(n+m).
Problem statement
• Analyze and find the time complexity of the below
function from the code snippet.
int k=1;
while(k<=n){
cout<<k<<endl;
k=k*2;
}
SOLUTION
• In the above code, the while loop will run logn times as k is multiplied
by 2 for every iteration. So, we can say the time complexity of the
above code is O(logn ).
Problem statement
• Analyze and find the time complexity of the below
function from the code snippet.
for(int i=n/2;i<=n;i++){
for(int j=1;j<=n;j=j*2){
cout<<i<<j<<endl;
}
}
SOLUTION
• In the above code, the outer loop will run (n/2) times and for each
value of i, the inner loop will run (logn) times. So, the total number of
operations is n/2*logn. We can say the time complexity of the above
code is O(n*logn ).
Problem statement
• Analyze and find the time complexity of the below
function from the code snippet.
if(i>j){
j==0? j++ : j--;
}
SOLUTION
• A Conditional statement takes O(1) time to execute. In the above code,
there are only two conditional statements. So, it takes constant time to
execute. Then we can conclude the time complexity of the above code
is O(1).
Problem statement
• Analyze and find the time complexity of the below
function from the code snippet.
int a = 0;
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j;
}
}
SOLUTION
• The above code runs total no of times
= N + (N – 1) + (N – 2) + … 1 + 0
= N * (N + 1) / 2
= 1/2 * N^2 + 1/2 * N
O(N^2) times.
Problem statement
• Analyze and find the time complexity of the below
function from the code snippet.
int i, j, k = 0;
for (i = n / 2; i <= n; i++) {
for (j = 2; j <= n; j = j * 2) {
k = k + n / 2;
}
}
SOLUTION
• If you notice, j keeps doubling till it is less than or equal to n. Several
times, we can double a number till it is less than n would be log(n).
Let’s take the examples here.
for n = 16, j = 2, 4, 8, 16
for n = 32, j = 2, 4, 8, 16, 32
So, j would run for O(log n) steps.
i runs for n/2 steps.
So, total steps = O(n/ 2 * log (n)) = O(n*logn)