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 = n; i > 0; i = i / 2)
for (j = 0; j < i; j = j + 1)
Print "*"
end for
end for- A. O(n)
- B. O(n log n)
- C. O(log n)
- D. O(n²)
Correct answer: A. O(n)
The inner loop runs i times and i halves each round: n + n/2 + n/4 + … < 2n. So the total work is linear, O(n). O(n log n) multiplies the log n rounds by the largest inner count n, which overestimates because the inner counts shrink geometrically.
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? for (i = 1; i <= n; i = i + 1) j = 1 while (j < i) j = j 2…
- 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…