Consider the following algorithms. Assume procedure A and procedure B take O(1) and O(1/n) unit of time respectively. Derive the time complexity of the algorithm in O-notation.
algorithm what(n)
begin
if n = 1 then
call A
else
begin
what(n-1);
call B(n)
end
end
A. O(1)
B. O(log n)
C. O(n)
D. O(n log n)
GATE 1999 · Algorithms · Time Complexity · medium
Answer: The time complexity of algorithm what(n) is O(n). Answer: C.
Set up the recurrence: Procedure B(n) takes O(1) per call (or O(1/n) which is bounded by O(1)). Each call to what(n) does O(1) work (call B) plus recursion on n-1. So T(n) = T(n-1) + c for some constant c.
Solve the recurrence: Unrolling: T(n) = T(n-1) + c = T(n-2) + 2c = ... = T(1) + (n-1)c = O(1) + (n-1)c = O(n). The algorithm makes n recursive calls each contributing O(1) work.