GATE CS 2004 · Asymptotic Analysis & Recurrences

MCQ · 1 mark · Problem PROG-DIVC-0153

Let A[1..n] be an array storing a bit (1 or 0) at each location, and let f(m) be a function whose time complexity is \(\Theta(m)\). Consider the following program fragment written in a C-like language:
counter = 0;
for (i = 1; i <= n; i++)
{
    if (A[i] == 1)
        counter++;
    else {
        f(counter);
        counter = 0;
    }
}
The complexity of this program fragment is
  1. A
    \(\Omega (n^{2})\)
  2. B
    \(\Omega (n \log n)\) and \(O (n^{2})\)
  3. C
    \(\Theta(n)\)
  4. D
    \(o(n)\)

Solve it on GATE DA practice →More Searching & Sorting Algorithms problems

Show the worked solution\[\boxed{\text{total} = \Theta(n)\ \text{for the loop} + \textstyle\sum \text{(arguments passed to } f)}\]The loop runs \(n\) times. f is called only at a 0, with the length of the run of 1s just before it, and then counter is reset to 0. Each 1 belongs to exactly one run, so the arguments of all the calls to f add up to at most \(n\).Total \(=\Theta(n)+O(n)=\Theta(n)\).Answer: C

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com