An Algorithm for rotating a sequence


An algorithm for rotating a sequence

I attended a job interview today, the interviewer asks me a question about how to rotate a sequence with a good space efficiency.
I believe I give him a terrible answer. And the interviewer gives me his answer, well, thanks him a lot.

So how to rotate a sequence? There is a sequence blow? 

+--+--+--+--+--+--+--+--+
| 1| 2| 3| 4| 5| 6| 7| 8|
+--+--+--+--+--+--+--+--+

then rotate the sequence to left by 3? what we get is as following.
+--+--+--+--+--+--+--+--+
| 4| 5| 6| 7| 8| 1| 2| 3|
+--+--+--+--+--+--+--+--+

So the following step to step tutorial is a space efficiency way.
  1. reverse the first 3 sequence.
  2. reverse the last (8 - 3) = 5 sequence.
  3. reverse the whole sequence.
Then, we get the result sequence which rotates to left by 3 items. I don't know whether it is the best way. I mean both the best space efficiency and time efficiency. 

orignal sequence
           n=3
    +--+--+--+--+--+--+--+--+
    | 1| 2| 3| 4| 5| 6| 7| 8|
    +--+--+--+--+--+--+--+--+

  step 1.  reverse first n sequence    
    +--+--+--+--+--+--+--+--+
    | 3| 2| 1| 4| 5| 6| 7| 8|
    +--+--+--+--+--+--+--+--+

  step 2. reverse last sequence 
    +--+--+--+--+--+--+--+--+
    | 3| 2| 1| 8| 7| 6| 5| 4|
    +--+--+--+--+--+--+--+--+

  step 3. reverse the whole sequence
    +--+--+--+--+--+--+--+--+
    | 4| 5| 6| 7| 8| 1| 2| 3|
    +--+--+--+--+--+--+--+--+

I wrote a sample code and upload into GitHub. Maybe I should add this algorithm into all my sequence related classes.

Comments

Popular posts from this blog

Bluedroid stack in android

How to setup a NAT server?

Network programming in elisp