Google Interview Question
Software Engineer in TestsI don't think d>0 always.
Necessary condition is i^2 >= n^2 - (j-0.25)^2
if we ignore 0.25, i^2 >= n^2-j^2
base condition is i=0, j=n, where condition won't be true.
In this easy case, it has nothing to do with d... i is still increased until a value from n/2 to n.
Worst case is O(n). Best case O(n/2) which is O(n).
You are right. Let me try to rephrase it so it becomes clearer:
In the "worst case" j is never decremented, and we need n iterations to finish. Perhaps this is an impossible run, but it is definitely impossible for a run to be any worse.
In the "best case" j is always decremented, and we need n/2 iterations to finish. Perhaps this is an impossible run, but it is definitely impossible for a run to be any better.
Hence O(n).
Thank you S.
void fn(int n)
- O(n) September 06, 2010{
int d,i=0;
int j=n;
while(i<j)
{
i++;
//d=i*i+(j-.25)*(j-.25)-n*n;
//if(d>0) j--;
}
}
We have O(n) complexity in that case
Then lets assume that d is ALWAYS be positive, than we have O(1/2 n) that is O(n) anyway