Rotate an Array using Reverses

Given an array A A and a number k k

We can rotate A A by k k spots.

For example

Given:

1
2
A = [1, 2, 3, 4, 5]
k = 3

We would get:

1
[4, 5, 1, 2, 3]

This can be done using a series of reverses.

How many calls to reverse() would you need?


The answer is 3.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Henry U
Nov 10, 2018

Let the lenght of A A be l l .

  1. Reverse the whole array
  2. Reverse the first l k l-k elements, with indices { 0 , , l k 1 } \{0, \ldots, l-k-1 \}
  3. Reverse the last l k l-k elements, with indices { l k , , l 1 } \{l-k, \ldots, l-1\}

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...