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 , number of rotations,  and indices to check, .
First we perform the two rotations:

Now return the values from the zero-based indices  and  as indicated in the  array.

Function Description
Complete the circularArrayRotation function in the editor below. It should return an array of integers representing the values at the specified indices.
circularArrayRotation has the following parameter(s):
  • a: an array of integers to rotate
  • k: an integer, the rotation count
  • queries: an array of integers, the indices to report.


Question from hackerrank.


Solution in C# -




class Solution {

    static int[] circularArrayRotation(int[] a, int k, int[] queries) {
        
        int len = a.Length;
        int[] ans = new int[queries.Length];
        int[] tempArr = new int[a.Length];
        k = k%len;
        for(int i=0; i<a.Length; i++) {
            int index = (i+k)%len;
            tempArr[index] = a[i];
        }

        for(int i=0; i<queries.Length; i++) {
            ans[i] = tempArr[queries[i]];
        }
        return ans;
    }

    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        string[] nkq = Console.ReadLine().Split(' ');

        int n = Convert.ToInt32(nkq[0]);

        int k = Convert.ToInt32(nkq[1]);

        int q = Convert.ToInt32(nkq[2]);

        int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp))
        ;

        int[] queries = new int [q];

        for (int i = 0; i < q; i++) {
            int queriesItem = Convert.ToInt32(Console.ReadLine());
            queries[i] = queriesItem;
        }

        int[] result = circularArrayRotation(a, k, queries);

        textWriter.WriteLine(string.Join("\n", result));

        textWriter.Flush();
        textWriter.Close();
    }
}

3 Comments

Post a Comment

Previous Post Next Post