Asymptotic Analysis & Recurrences
![Question 82, GATE 2004: A[1..n] stores bits. Function f(m) takes Θ(m) time for positive m, with constant bookkeeping for m=0. What is the complexity of:
counter=0;
for(i=1;i<=n;i++) {
if(A[i]==1) counter++;
else { f(counter); counter=0; }
}
Option D is little-o in the clearer GateForum reproduction.
Options:
(A) Ω(n²)
(B) Ω(n log n) and O(n²)
(C) Θ(n)
(D) o(n)](../../assets/questions/CS-2004-Q82-1.webp)
Answer & solution
Answer: C (no official key was published)
1. The counter measures the current consecutive run of ones. A zero invokes f on that run length and then resets the counter.
2. The lengths passed to all calls sum to at most n, because no position containing one belongs to two completed runs. Thus all calls together take O(n), including O(1) bookkeeping for zero-length runs, while the loop itself always performs n iterations and costs Ω(n).
3. Total complexity is Θ(n), C. A final run without a trailing zero does not increase this bound.
4. Teaching check: Charge each unit of f’s linear work to one of the ones in its completed run. No one belongs to two runs, so total charged work is linear. The always-executed loop supplies the matching linear lower bound; little-o(n) cannot describe it.