Let be an array storing a bit ( or ) at each location, and is a function whose time complexity is . 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
View worked solution
Answer: C
To find the total time complexity of the program fragment, let us analyze the work done in each iteration of the loop:
- Loop Overhead: The loop runs exactly times, contributing time for index increments and conditional checks.
- Inside the Loop:
- When , we increment
counter, taking time. - When , we call and reset
counterto . Since , this call takes time proportional to the number of consecutive s seen since the last .
- When , we increment
Let the lengths of consecutive blocks of s in the array be . Since the total number of elements in the array is , the sum of the lengths of these blocks cannot exceed :
The total time spent executing the function across all iterations is:
Combining the loop overhead and the function calls, the overall time complexity is .
Free practice · Your answers on this page are not saved.
