In a recent interview I was asked:
Find the middle element of a sorted List of unknown length starting from the first position.
I responded with this:
Have 2 position counters:
counter1
counter2
Increment counter1 by 1 and counter2 by 2. When counter 2 reaches the end of the list counter 1 will be in the middle. I feel that this isn’t efficient because I am revisiting nodes I have already seen. Either way, is there a more efficient algorithm?
Assuming a linked list, you can do it while visiting arbitrarily-close-to N of the items.
To do 5/4 N:
When you hit the end of the list, the before-last anchor is before the mid-point but at least half way there already. So N for the full iteration + at most 1/4 N for the anchor = 5/4 N.
Dropping anchors more frequently, such as at every ceiling power of 1.5^th item, gets you as close to N as needed (at the cost of tracking more anchors; but for any given X as the power step, the asymptotic memory is constant).