ProgrammingHardTCS Digital · Infosys SP
What is the time complexity of the following pseudocode, as a function of n?
What is the time complexity of the following pseudocode, as a function of n?
for (each i from 1 to n)
j = 1
while (j < i)
j = j * 2
end while
end for- A. O(n)
- B. O(n²)
- C. O(log n)
- D. O(n log n)
Correct answer: D. O(n log n)
For each i the while loop doubles j up to i, about log₂ i times. Σ log i for i = 1..n is log(n!) ≈ n log n, so the total is O(n log n).
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What is the time complexity of the following pseudocode on an array of n elements? Stack st = empty for (each i from 0 to n - 1) while (st…
- What will be the output of the following pseudocode? (c ? x : y evaluates x if c is true, otherwise y) Integer marks[6] = {92, 75, 60, 88…
- What will be the output of the following pseudocode? (continue in a do-while loop goes straight to the while test) Integer x = 1, c = 0 do…
- What will be the output of the following pseudocode? (s[i] - '0' turns a digit character into its value; strings are indexed from 0)…
- What will be the output of the following pseudocode? (+ joins strings) Integer count = 0 String third = "" Procedure gen(String s, Integer…
- What will be the output of the following pseudocode? Integer s = 0 for (each i from 1 to 49) if (i mod 3 == 0 OR i mod 5 == 0) s = s + i…