Given an array of n
integers and a number, d
, perform left rotations on the array. Then print the updated array as a single line of space-separated integers.
Sample Input:
5 4
1 2 3 4 5
The first line contains two space-separated integers denoting the respective values of n
(the number of integers) and d
(the number of left rotations you must perform).
The second line contains n
space-separated integers describing the respective elements of the array's initial state.
Sample Output:
5 1 2 3 4
static void Main(String[] args)
{
string[] arr_temp = Console.ReadLine().Split(' ');
int n = Int32.Parse(arr_temp[0]);
int d = Int32.Parse(arr_temp[1]);
string[] arr = Console.ReadLine().Split(' ');
string[] ans = new string[n];
for (int i = 0; i < n; ++i)
{
ans[(i + n - d) % n] = arr[i];
}
for (int j = 0; j < n; ++j)
{
Console.Write(ans[j] + " ");
}
}
How to use less memory to solve this problem?
Do you really need to physically move anything? If not, you could just shift the index instead.
I've solve the challange from Hackerrank by following code. Hope it helps.
}
Isn't using IEnumerables better? Since It won't perform all of those maths, won't allocate that many arrays, etc
IF you don't actually need to return an array, you can even remove the .ToArray() and return an IEnumerable
Usage:
Actually you asked 2 questions:
and
Usually efficiency and low memory usage are mutually exclusive. So I'm going to answer your second question, still providing the most efficient implementation under that memory constraint.
The following method can be used for both left (passing negative count) or right (passing positive count) rotation. It uses O(1) space (single element) and O(n * min(d, n - d)) array element copy operations (O(min(d, n - d)) array block copy operations). In the worst case scenario it performs O(n / 2) block copy operations.
The algorithm is utilizing the fact that
Here it is:
Sample usage like in your example:
This is my attempt. It is easy, but for some reason it timed out on big chunks of data:
I have tried to used stack and queue in C# to achieve the output as follows: