ProgrammingVery hardProduct company OA · code-tracing level
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 (i = 1; i <= n; i = i + 1)
j = 1
while (j < i)
j = j * 2
end while
end for- A. O(n)
- B. O(n log n)
- C. O(n²)
- D. O(log² n)
Correct answer: B. O(n log n)
For each i the while loop doubles j until it reaches i, about log₂ i steps. Summing log₂ i over i = 1…n gives log₂(n!) ≈ n log₂ n, so the complexity is O(n log n). O(n) treats the inner loop as constant time; O(n²) treats it as linear.
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, as a function of n? i = 2 while (i <= n) i = i i end while
- What is the time complexity of the following pseudocode, as a function of n? for (i = 1; i i <= n; i = i + 1) for (j = 1; j <= n; j = j 2)…
- What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division; 'from … to …' includes both ends.)…
- What will be the output of the following pseudocode? Integer c = 0, d, k for (each x from 1 to 30) k = 0 for (each d from 1 to x) if (x…
- What will be the output of the following pseudocode? (Array positions run from 1 to 10.) Integer alive[1..10] = all 1, left = 10, pos = 0…
- What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, << and >> are shifts.) Integer x = 22, r = 0 for…