I am new to C# and have tried to solve a problem statement from CodeChef:
Problem statement
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 \le N \le 100000\$
- \$1 \le M \le 100000\$
- \$1 \le d \le N\$, in all the queries
- \$1 \le \$ elements of A \$ \le 1000000\$
The array A and the queries of the type R are 1-based.
Example
Input:
5 5 5 4 3 3 9 R 1 C 4 R 5 A 3 R 2
Output:
5 3 3
My Code:
using System;
using System.Collections;
using System.Text;
namespace RotationSeptChallenge
{
class Program
{
public static void Main(string[] args)
{
string nm = Console.ReadLine();
string n = nm.Split(' ')[0];
string m = nm.Split(' ')[1];
int loopvar = int.Parse(m);
string[] arr = new string[int.Parse(n)];
var temp = Console.ReadLine().Split(' ');
for (int i = 0; i < temp.Length; i++)
{
arr[i] = temp[i];
}
for (int loop = 0; loop < loopvar; loop++)
{
var optionanddistance = Console.ReadLine();
char option = char.Parse(optionanddistance.Split(' ')[0]);
int distance = int.Parse(optionanddistance.Split(' ')[1]);
if (option == 'C')
{
ArrayList tempAL = new ArrayList();
tempAL.AddRange(arr);
tempAL.CopyTo(distance, arr, 0, arr.Length - distance);
tempAL.CopyTo(0, arr, arr.Length - distance, distance);
}
if (option == 'A')
{
ArrayList tempAL = new ArrayList();
tempAL.AddRange(arr);
tempAL.CopyTo(arr.Length - distance,arr,0,distance);
tempAL.CopyTo(0,arr,distance,arr.Length - distance);
}
if (option == 'R')
{
Console.WriteLine(arr[distance - 1]);
}
}
}
}
}
My solution seems to be right when I tried with a few sample outputs. However, Time Limit Exceeded was the result of my Submission. The time Limit is set to 1 sec and my solution takes >1sec. What seems to be the problem? How can I optimize this code to perform better?