I thought the time complexity of the code below is O(n^2) or O(n*logn).
int j = 0;
for(i = 0; i < n; ++i) {
while(j < n && arr[i] < arr[j]) {
j++;
}
}
However, the answer page says it is O(n).
I can't understand why it becomes so.
My (silly) opinions were the following:
- The time complexity is O(n^2) since there are two loop running
n
times.arr[i] < arr[j]
may affect thewhile
loop, but it doesn't matter. - The time complexity is O(n*logn) since the while loop may run less than
n
times becausearr[j]
can be smaller thanarr[i]
during the loop. As a result,while
loop would run forlog(n)
times.
Could you explain why was my answer wrong and why the correct time complexity is O(n)?