Array Left Rotation in C#

Problem source: Left Rotation – Hackerrank

Input: 

n = number of items in array

r = number of rotations

arr = integer array

Output:

Array items after “r” left rotation.

Example:

n = 5

r = 3

Arr = [1, 2, 3, 4, 5]

Output:

4 5 1 2 3

Explanation: 

Original Array: 1 2 3 4 5

1st rotation: 2 3 4 5 1

2nd rotation: 3 4 5 1 2

3rd rotation: 4 5 1 2 3

Algorithm: 

  1. If r % n = 0 that means there is no need of rotation because array items will be in same position after rotation.
  2. If r % n = i then we’ll split our original array into two parts.
    1. First part will have items from i to n.
    2. Second part will have items form 0 to i -1;
  3. Print this new array.

C# code:

static void Main(String[] args)
{
    var strInput = Console.ReadLine().Split(' ');
    var n = Convert.ToInt32(strInput[0]);
    var r = Convert.ToInt32(strInput[1]);
    var arr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
    var finalRotationCount = r % n;
    if (finalRotationCount > 0)
    {
        var temp = new int[n];
        for (int i = 0; i < n - finalRotationCount; i++)
        {
            temp[i] = arr[finalRotationCount + i];
        }

        for (int i = 0; i < finalRotationCount; i++)
        {
            temp[n - finalRotationCount + i] = arr[i];
        }

        arr = temp;
    }
    Console.WriteLine(string.Join(" ", arr));
    Console.ReadKey();
}

 

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