ISRO Scientist/Engineer CSE 2020Algorithms › Time Complexity and Recurrences
ISRO Scientist/Engineer CSE 2020 PYQ: What is the complexity of the following code? sum=0; for(i=1;i<=n;i*=2) for(j=1;j<=n;j++) sum++; Which of…
What is the complexity of the following code?
sum=0;
for(i=1;i<=n;i*=2)
for(j=1;j<=n;j++)
sum++; Which of the following is not a valid string?
- A$O(n^2)$
- B$O(n\log\ n)$
- C$O(n)$Correct answer
- D$O(n\log\ n\log\ n)$
Answer
(C) $O(n)$
Approach
The nested loop has an outer for (i = 1; i <= n; i = 2). The values of i are 1, 2, 4, 8, ..., so the outer loop runs about log2(n) times, i.e., Θ(log n). The inner for (j = 1; j <= n; j++) always runs exactly n times, independent of i. Therefore the statement sum++ executes n Θ(log n) = Θ(n log n) times. The code's tight bound is Θ(n log n). The question asks which option is NOT a valid complexity for this code. A complexity O(f(n)) is valid as an upper bound only if f(n) grows at least as fast as n log n asymptotically. O(n log n) is the tight bound and is valid. $O(n^2)$ is valid because $n log n ≤ n^2$ for large n. O(n log n log n) is valid because n log n ≤ n log n log n for sufficiently large n (when log n ≥ 1). However, O(n) is not a valid upper bound: n log n is not O(n), since n log n divided by n is log n, which grows without bound. Thus the only invalid complexity is O(n), corresponding to option C. The handwritten image confirms this: it computes TC = n(log n) and circles option C. Note that “valid string” in the prompt appears to be a transcription error for “valid complexity” or “valid asymptotic bound”; regardless, C is the unique correct choice.
Reviewed by ISRO IQ Editorial Team.