Amazon Interview Question

Given an array of integers, rotate it one position.

Interview Answers

Anonymous

Jan 17, 2016

1-divide the array in 2 of rotation order (e.g. num rotation =3 , then a1[N-3] , a2[3-N] 2-Reverse the first array 3-reverse the second array 3-reverse the whole array Note that the functions that do the reverse is not creating new arrays. Then with this you have time complexity O(n) and space complexity O(1) because you're using only one array in memory

1

Anonymous

May 23, 2015

I used a queue to record the array, pop and then push.

Anonymous

Feb 22, 2016

The general case (rotate k positions) int[] rotateArray(int[] A, int k) { if (k==0) return A; // rotating 0 positions is the original array int savedVal = A[k-1%A.length] for (int i = 0; i < A.length; ++i) { int temp = A[(i+k)%A.length]; A[(i+k)%A.length] = savedVal; savedVal = temp; } A[k-1%A.length] = savedVal; return A; }