ProgrammingVery hardGoldman Sachs OA · Amazon 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?
Function f(Integer n)
if (n <= 1)
return 1
end if
return f(n / 2) + f(n / 2)
End Function- A. O(log n)
- B. O(n log n)
- C. O(2ⁿ)
- D. O(n)
Correct answer: D. O(n)
T(n) = 2T(n/2) + O(1). The call tree has log₂ n levels but doubles in width each time, ending with about n leaves, so there are about 2n calls: O(n). Computing f(n / 2) once and doubling it would make it O(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, as a function of n? Procedure g(Integer n) if (n <= 1) return for (each i from 1…
- What will be the output of the following pseudocode? Integer m[3][3] = {{11, 2, 4}, {4, 5, 6}, {10, 8, -12}} Integer d1 = 0, d2 = 0 for…
- What will be the output of the following pseudocode? (/ truncates toward zero and mod keeps the sign of the dividend (as in C)) Integer x…
- What will be the output of the following pseudocode? Boolean seen[0..6] = all false Integer c = 0 for (each i from 1 to 20) Integer r = (i…
- What will be the output of the following pseudocode? Function gcd(Integer a, Integer b) if (b == 0) return a return gcd(b, a mod b) End…
- What will be the output of the following pseudocode? String s = "hello world of code" Integer changes = 0 for (each i from 0 to length(s)…