3 ms·
You cannot define an algorithm given this specification. (ie. you cannot determine when to stop). Take for example the list (1 2 3 1 2 3 1 2 3) with min=1 and
by informatimago 11y ago
You cannot define an algorithm given this specification.
(ie. you cannot determine when to stop).
Take for example the list (1 2 3 1 2 3 1 2 3) with min=1 and max=3.
Notice that there is no operation giving you the number of element of the list, and no operation giving you access to the elements of the list: you cannot copy elements to a temporary storage, or replace one element for example with a guard value such as min-1.
Therefore you can only call compare, which tells you whether the first and second elements are in order or not, and from that you can only swap or not. Then to make progress, you have to rotate.
You can count the number of rotate and the number of swaps, and if you knew the total number N of elements in the list, you could say that after N-1 negative compare your list is sorted.
But since you don't know N, you cannot stop. Since you cannot read the elements of the list, you cannot even know that you've reach one of the min (if you knew N you could know that even without reading, by noticing that you always had to swap to keep it, but you don't).
Your code cheats, since it's use the length of the list (it's not one of the three operations allowed).
- davidplatt 11y agoYeah, I'm aware of the cheating by calling the length. I couldn't figure out a different way. I agree with you. This actually was not from my interview. A friend said he was interviewed over the phone with this question and posed it to me. After he first told me it, I assumed he misinterpreted it; I sent a bubble sort. Then he got defensive and insisted on the interpretation I re-wrote in the OP. I wasted a lot of time brute forcing it on paper before I could find a pattern, and still couldn't figure it out without knowing the length (and therefore traversing the list past the second node).