I solved the Circular-Array-Rotation problem on HackerRank. I conceded defeat and looked at the answers given on HackerRank itself but the ones I saw used things like vectors, which are concepts I'm a noob at as my knowledge of C++ thus far extends only as far as virtual functions and classes and such (junior COE student). So here's the description of the problem:
John Watson performs an operation called a right circular rotation on an array of integers, \$a[0], a[1], \dotsc, a[n-1]\$. After performing one right circular rotation operation, the array is transformed from \$a[0], a[1], \dotsc, a[n-1]\$ to \$a[n-1], a[0], \dotsc, a[n-2]\$.
Watson performs this operation \$k\$ times. To test Sherlock's ability to identify the current element at a particular position in the rotated array, Watson asks \$q\$ queries, where each query consists of a single integer, \$m\$, for which you must print the element at index \$m\$ in the rotated array (i.e., the value of \$a[m]\$).
Input Format
The first line contains 3 space-separated integers, \$n\$, \$k\$, and \$q\$, respectively.
The second line contains \$n\$ space-separated integers, where each integer \$i\$ describes array element \$a[i]\$ (where \$0 \le i < n\$). Each of the \$q\$ subsequent lines contains a single integer denoting \$m\$.
Constraints
\begin{align*} 1 &\le n &&\le 10^5 \\ 1 &\le a[i] &&\le 10^5 \\ 1 &\le k &&\le 10^5 \\ 1 &\le q &&\le 500 \\ 0 &\le m &&\le n - 1 \end{align*}
Output Format
For each query, print the value of the element at index \$m\$ of the rotated array on a new line.
Sample Input
3 2 3 1 2 3 0 1 2
Sample Output
2 3 1
Explanation
After the first rotation, the array becomes \$[3,1,2]\$. After the second (and final) rotation, the array becomes \$[2,3,1]\$.
Let's refer to the array's final state as array \$b\$. For each query, we just have to print the value of \$b[m]\$ on a new line:
- \$m = 0\$, so we print
0
on a new line.- \$m = 1\$, so we print
1
on a new line.- \$m = 2\$, so we print
2
on a new line.
This is my code, sadly it only works for a few of the test cases, and times out for the others. Any feedback welcome, including suggestions on learning new methods or anything.
int n; int k; int q; cin >> n >> k >> q; int *arr = new int[n]; int *query = new int[q]; for (int i = 0; i < n; i++) { cin >> arr[i]; } for (int j = 0; j < q; j++) { cin >> query[j]; } int *arr2 = new int[n]; int count = 0; while (count < k) { int temp = arr[n - 1]; for (int j = 1; j < n; j++) { arr2[j] = arr[j - 1]; } arr2[0] = temp; for (int j = 0; j < n; j++) { arr[j] = arr2[j]; } count++; } for (int m = 0; m < q; m++) { cout << arr2[query[m]] << endl; }