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?
i = n
while (i > 1)
j = i
while (j < n)
j = j * 2
end while
i = i / 2
end while- A. O(log n)
- B. O(n)
- C. O(n log n)
- D. O(log² n)
Correct answer: D. O(log² n)
The outer loop runs about log n times with i = n/2ᵏ. For that i, the inner loop doubles j from n/2ᵏ up to n, which takes k steps. Total 0 + 1 + … + log n ≈ (log n)²/2, i.e. O(log² n).
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer c = 0, i = 1, j while…
- What will be the output of the following pseudocode? (stop ends the program; code(c) gives a letter's character code) String s =…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[8] = {1, 1, 2, 2, 2, 3, 5, 5} Integer k = 1 for…
- What will be the output of the following pseudocode? (strings are indexed from 0) String x = "AGGTAB", y = "GXTXAYB" Integer L[0..6][0..7]…
- What will be the output of the following pseudocode? Integer wt[3] = {2, 3, 4}, val[3] = {3, 5, 6} Integer best[0..6] = all 0 for (each i…
- What will be the output of the following pseudocode? Integer lcm = 18, steps = 0 Integer a = 12, b = 18 while (lcm mod a != 0 OR lcm mod b…