Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, the theory: Rearrange the elements in 'permutation cycles'. Take an element and place it at its new position, displacing the element that is currently there. Then you take that displaced element and put it in its new position. This displaces yet another element, so rinse and repeat. If the element displaced belongs to the position of the element you first started with, you have completed one cycle.</p> <p>Actually, yours is a special case of the question I asked <a href="https://stackoverflow.com/questions/1683020/possible-to-rearrange-an-array-in-place-in-on">here</a>, which was: How do you rearrange an array to any given order in O(N) time and O(1) space? In my question, the rearranged positions are described by an array of numbers, where the number at the nth position specifies the index of the element in the original array.</p> <p>However, you don't have this additional array in your problem, and allocating it would take O(N) space. Fortunately, we can calculate the value of any element in this array on the fly, like this:</p> <pre><code>int rearrange_pos(int x) { if (x % 2 == 0) return x / 2; else return (x - 1) / 2 + n; // where n is half the size of the total array } </code></pre> <p>I won't duplicate the rearranging algorithm itself here; it can be found in the accepted answer for my question.</p> <p><b>Edit:</b> As Jason has pointed out, the answer I linked to still needs to allocate an array of bools, making it O(N) space. This is because a permutation can be made up of multiple cycles. I've been trying to eliminate the need for this array for your special case, but without success.. There doesn't seem to be any usable pattern. Maybe someone else can help you here.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload