Recently, I encountered this coding exercise on codility and the idea is
A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place.
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes.
Write a function:
class Solution { public int[] CyclicRotation(int[] A, int K); }
that, given a zero-indexed array A consisting of N integers and an integer K, returns the array A rotated K times.
For example, given array A = [3, 8, 9, 7, 6] and K = 3
the function should return [9, 7, 6, 3, 8].
Assume that:
N and K are integers within the range [0..100]; each element of array A is an integer within the range [−1,000..1,000].
My approach was if the array has zero or 1 element, the array given is returned else thne for loop is executed. I also added the new array to extract a subset of the array which was meant to be shifted and the first element of Array A is swapped with the last element. Finally, a new list is created with aim to achieve the insert the first element A[0] after being swapped.
public static int[] CyclicRotation(int[] A, int K)
{
//Rotate an array to the right by a given number of steps.
// eg k= 1 A = [3, 8, 9, 7, 6] the result is [6, 3, 8, 9, 7]
// eg k= 3 A = [3, 8, 9, 7, 6] the result is [9, 7, 6, 3, 8]
if(A.Length== 0 || A.Length ==1)
{
return A;
}
int lastElement;
int[] newArray = new int[A.Length];
List<int> listOfNumbers = new List<int>();
for (int i = 1; i < K+1; i++)
{
lastElement = A[A.Length - 1];
newArray = A.Take(A.Length - 1).ToArray();
listOfNumbers = newArray.ToList<int>();
listOfNumbers.Insert(0, lastElement);
A = listOfNumbers.ToArray();
newArray = A;
}
return newArray;
}
I believe there is room for improvements. Any suggestions would be appreciated.
lastElement
andnewArray
why not just subtract the length the second you getA
? \$\endgroup\$K > N
? \$\endgroup\$[1,2,3]
all solutions are great. Consider an array of 10B length and you will see that any memory allocation appear to be very costly. \$\endgroup\$