ProgrammingVery hardAmazon OA · Goldman Sachs OA
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 * 2)
for (j = 0; j < i; j = j + 1)
count = count + 1
end for
end for- A. O(n log n)
- B. O(log n)
- C. O(n²)
- D. O(n)
Correct answer: D. O(n)
The inner loop runs i times for i = 1, 2, 4, …, below n, and 1 + 2 + 4 + … + 2ᵏ < 2n. So the total work is O(n), not O(n log n) as the nested shape suggests.
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 (n > 2)? while (n > 2) n = squareRoot(n) // integer square…
- What will be the output of the following pseudocode? Integer coins[3] = {1, 2, 5} Integer ways[0..6] = all 0 ways[0] = 1 for (each a from…
- What will be the output of the following pseudocode? (code(c) gives a letter's character code; strings are indexed from 0) String s =…
- What will be the output of the following pseudocode? // list: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL Node slow = head, fast = head while…
- What will be the output of the following pseudocode? Integer m[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Integer j for (each d from 0 to…
- What will be the output of the following pseudocode? (strings are indexed from 0) Procedure perm(String s, Integer l) // s is passed by…