A doubt related to Time Complexity !
Consider the following snippet:
for(i = n-1; i >= 0; i--)
{
if(str[i] == ' ')
{
i += 2; // I am just incrementing it by 2, so that i can retrieve i+1
continue;
}
// rest of the code with many similar increments of i
}
Say suppose the loop never turns up into infinity and If I traverse through the loop with many such increments and decrements, I am sure the complexity would not be of order N or N Square. But is there an开发者_开发知识库y generalised complexity for such kind of solutions ??
P.S: I know it`s the worst code, but still wanted to give it a try :-)
This is an infinite loop (infinite complexity) if you have a space in your string. Since you are using continue
, it goes back to for
and it starts from i+2.
Lets assume that str
does not change over the course of this traversal.
You are traversing str
backwards and when you hit a space you move the index forward by one i.e. it would hit the space again in the next decrement and then move it forward again i.e. your claim that the loop is not infinite, does not seem valid.
If no mutable state affects the path taken by i
, then either you go into an infinite loop, or you exit the loop in n
or less steps. In the latter case, the worst case performance will be O(N)
.
If the loop mutates some other state, and that state affects the path, then it is impossible to predict the complexity without understanding the state and the mutation process.
(As written, the code will go into an infinite loop ... unless the section at the end of the loop does something to prevent it.)
精彩评论