This code is to solve the Hacker Rank problem array left rotation.
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = 0;
temp = a[0];
for (int intK = 0; intK < a.Length; intK++)
{
a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
}
}
return a;
}
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
This program works fine, but it takes too long with some examples. How can I improve it?
O(n)
becauseSkip
is not clever... as far as I know it iterates the collection to skip the items. \$\endgroup\$2n
, or200n
for that matter, is stillO(n)
\$\endgroup\$