Circular Array Rotation using LinkedList

HackerRank – Circular Array Rotation

Programming Language – C#

Description: 

John Watson knows of an operation called a right circular rotation on an array of integers. One rotation operation moves the last array element to the first position and shifts all remaining elements right one. To test Sherlock’s abilities, Watson provides Sherlock with an array of integers. Sherlock is to perform the rotation operation a number of times then determine the value of the element at a given position.

For each array, perform a number of right circular rotations and return the value of the element at a given index.

For example, array a = [3,4,5], number of rotations, k=2 and indices to check, m=[1,2].

You can check full question click here

Solution Circular Array Rotation:

1) Use the LinkedList – using System.Collections.Generic

2) We need to remove the last node and add it into 1st position.

3) Get the queries data

static int[] circularArrayRotation(int[] a, int k, int[] queries)
{
LinkedList<int> l = new LinkedList<int>(a);
while (k > 0)
{
var removed = l.Last;
l.RemoveLast();
l.AddFirst(removed);
k–;
}
int[] data = l.ToArray();
int[] output = newint[queries.Length];
for (int i = 0; i < queries.Length; i++)
{
output[i] = Convert.ToInt32(data[queries[i]]);
}
return output;
}

Happy Coding!!

Leave a Reply

Discover more from The Engineering Behind Enterprise AI

Subscribe now to keep reading and get access to the full archive.

Continue reading