What is the complexity of the following code? sum=0;        for (i=1; I <= n; i*=2)                 for(j=1; j<=n;j++)                                 sum++;

What is the complexity of the following code? sum=0;        for (i=1; I <= n; i*=2)                 for(j=1; j<=n;j++)                                 sum++; Correct Answer O(n log n)

Code

Time complexity

sum = 0

O(1)

for (i=1; I <= n; i*=2)

O(logn) because I is incremented exponentially and loop will run for less number of times than n.

for(j=1; j<=n; j++)

O(n) because j is incremented linearly and loop will run for n number of times.

sum++

O(1)

 

Total time complexity = O(n×logn)

Important Point:

In original ISRO CS 2020, and extra data was present “Which of the following is not a valid string?”

Which made this question ambiguous and hence excluded from evaluation.

Related Questions