Array Rotation

Rotate an n-element vector left by i positions in time proportional to n with just a dozen bytes of extra space. For instance, with n=8 and i=3, the vector abcdefgh is rotated to defghabc

Answer:


Step 1: reverse the array.
abcdefgh -> hgfedcba
Step 2: reverse 0 to n-i-1
hgfedcba -> defghcba
Step 3: reverse n-i to n
defghabc

No comments: