rotate array by C slots in O(N) !O(CN) #AbInitio IV

Can write a python code as a practice.

A: find the largest common denominator. If it’s 3, then the array consists of 3 interleaved subarrays. We will “process” each subarray simultaneously since they are completely independent. First subarray consists of Slots 0,3,6,9… Within each subarray, K’ and N’ (scaled down by the denominator) have no common denominator, therefore an iteration will visit every element exactly once until we revisit the first element.

Q: rotates a long array (N elements) by K positions. Both N and K are potentially large, so we need 1) time efficiency 2) memory efficiency. Ideally, O(1) space and O(N) time.

If K = 1, then just shift every element right, rotating the last element to the head. If K = 2, just repeat. But K is large.

You can assume it’s an array of pointers, or you can assume it’s an array of integers — Same challenge. Note unlike linked lists, array provides random access so you can access array[9000] in constant time.

The brute-force solution requires O(K*N), shifting all N elements K times.

–analysis

Without loss of generality, let’s rotate by 3 slots. If N is multiple of 3, like 30, then there are 3 individual, independent, interleaved arrays of 10. Just rotate each by 1 slot.

If N is not a multiple of 3, like 31, then view the array as a circular array and we hop by 3 slots each time. So our journey will start from position 0 (or any position) and cover every position and come back to the starting position. This can be proven by contradiction —

Sooner or later we must be re-visiting some position. We know that position is reachable from position 0, so the distance between them must be multiple of 3. So position 0 must be revisited.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s