sirine.ch sirine.ch - 4 months ago 508
Java Question

I get “Terminated due to timeout” in some test cases in hackerRank,how do I solve this?

I'm trying to solve this problem in HackerRank, but I get timed out error in some test cases. any suggestions?
the following is my code;
most test cases work, but others time out.

public class Solution
{
static int[] rotation(int[] arr)
{
int[] rot = new int[arr.length];
rot[0] = arr[arr.length - 1];
System.arraycopy(arr, 0, rot, 1, arr.length - 1);
return rot;
}

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int q = in.nextInt();
int[] T = new int[n];

for (int i = 0; i < n; i++) {
T[i] = in.nextInt();
}

int[] indexes = new int[q];
for (int j = 0; j < q; j++) {
indexes[j] = in.nextInt();
}
in.close();

// Rotations
for (int ai = 0; ai < k; ai++) {
T = rotation(T);
}

// Queries
for (int qi = 0; qi < q; qi++) {
System.out.println(T[indexes[qi]]);
}
}
}

Answer

Maybe rotating the array in-place instead of creating a new one for each rotation?

static void rotation(int[] arr)
{
    int temp = arr[arr.length - 1];
    System.arraycopy(arr, 0, arr, 1, arr.length - 1);
    arr[0] = temp;
}

And then later:

T = rotation(T);

Becomes:

rotation(T);

You could also optimize for the case where k is less than n, but I'll leave that as an exercise for you if you need it.