Can you please help me in reducing the complexity of the below code? The problem statement can be found here.
You are given an array A of N integers. You are to fulfill M queries. Each query has one of the following three types:
C d : Rotate the array A clockwise by d units.
A d : Rotate the array A anticlockwise by d units.
R d : Query for the value of the element, currently being the d-th in the array A.Input
The first line contains two numbers - N and M respectively. The next line contains N space separated Integers, denoting the array A. Each of the following M lines contains a query in the one of the forms described above.
Output
For each query of type R output the answer on a separate line.
Constraints
1 ≤ N ≤ 100000
1 ≤ M ≤ 100000
1 ≤ d ≤ N, in all the queries
1 ≤ elements of A ≤ 1000000The array A and the queries of the type R are 1-based.
The solution in Java manages to solve the problem but is facing a time limit exceeded issue, so please advise me on how to optimize the code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
public static void main (String args[]) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String not[]=in.readLine().trim().split(" ");
int n=Integer.parseInt(not[0]);
int q=Integer.parseInt(not[1]);
String s[]=in.readLine().trim().split(" ");
ArrayList<Integer> sarray=new ArrayList<Integer>();
for(int i=0;i<n;i++)
{
sarray.add(Integer.parseInt(s[i]));
}
for(int j=0;j<q;j++)
{
String r[]=in.readLine().trim().split(" ");
if(!r[0].equals("R"))
sarray=swap(sarray,n,Integer.parseInt(r[1]),r[0]);
else
System.out.println(sarray.get(Integer.parseInt(r[1])-1));
}
}
private static ArrayList<Integer> swap(ArrayList<Integer> arr, int n, int d,String c) {
// TODO Auto-generated method stub
int i, j;
int temp;
for(j = 0; j < d; j++)
{
//rotate right once
if(c.equals("A"))
{
temp = arr.get(n - 1);
for(i = n - 1; i > 0; i--)
arr.set(i,arr.get(i-1));
arr.set(0,temp);
}
else if(c.equals("C"))
{
temp = arr.get(0);
for(i = 0; i < n-1; i++)
arr.set(i,arr.get(i + 1));
arr.set(n - 1,temp);
}
}
return arr;
}
}