GATE | GATE-CS-2004 | Question 82

Let A[1, …, n] be an array storing a bit (1 or 0) at each location, and f(m) is a function whose time complexity is θ(m). Consider the following program fragment written in a C like language:

filter_none

edit
close

play_arrow

link
brightness_4
code

counter = 0;
for (i = 1; i < = n; i++)
      if (A[i] == 1) 
         counter++;
      else {
         f(counter); 
         counter = 0;
      }
}

chevron_right


The complexity of this program fragment is
(A) Ω(n2)
(B) Ω(nlog n) and O(n2)
(C) θ(n)
(D) O(n)


Answer: (C)

Explanation: Please note that inside the else condition, f() is called first, then counter is set to 0.

Consider the following cases:



a) All 1s in A[]: Time taken is Θ(n) as
                  only counter++ is executed n times.

b) All 0s in A[]: Time taken is Θ(n) as
                  only f(0) is called n times

c) Half 1s, then half 0s: Time taken is  Θ(n) as
                  only f(n/2) is called once.


Quiz of this Question



My Personal Notes arrow_drop_up

Improved By : OnkarMarbhal



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.