Hi John I thought the same but in the end figured why it doesn’t count as a nested loop and I will try and explain.
Lets take an example I made up which is similar to the one of the examples:
7, 0, 1, 2, 3, 4, 5, 6
We have 8 numbers in our input from 0
to 7
and essentially missing 8
I have added the numbers in this sequence as it presents the worst case scenario in terms of swapping inside the while loop.
Let’s walk through the iterations manually which I believe will help visualise the time complexity.
Starting point → 7, 0, 1, 2, 3, 4, 5, 6
Iteration 1 → 6, 0, 1, 2, 3, 4, 5, 7
Iteration 2 → 5, 0, 1, 2, 3, 4, 6, 7
Iteration 3 → 4, 0, 1, 2, 3, 5, 6, 7
Iteration 4 → 3, 0, 1, 2, 4, 5, 6, 7
Iteration 5 → 2, 0, 1, 3, 4, 5, 6, 7
Iteration 6 → 1, 0, 2, 3, 4, 5, 6, 7
Iteration 7 → 0, 1, 2, 3, 4, 5, 6, 7
We have performed 7
iterations over an array of length 8
thus O(n - 1)
Our index pointer is still at 0
but now since everything is sorted we wont have any further swaps in subsequent iterations so the we iterate again until i
< n
thus O(n - 1)
the example said O(n)
but I say O(n - 1)
since we did the 0th
when we replaced items.
Finally we iterate once more until we find the missing number thus another O(n)
In total we have O(n - 1) + O(n - 1) + O(n)
I hope that has cleared this for you.