HackerRank Python - some test cases get "Terminated due to timeout", how can i optimize the code?
<p>Currently, on HackerRank, I am trying to solve the <a href="https://www.hackerrank.com/challenges/circular-array-rotation?h_r=next-challenge&amp;h_v=zen" rel="nofollow">Circular Array Rotation</a> problem. Most of the test cases work, but some are "Terminated due to timeout".</p>

<p>How can I change my code to optimise it?</p>

<pre><code>#!/bin/python3

import sys


n,k,q = input().strip().split(' ')
n,k,q = [int(n),int(k),int(q)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]

m = []
for a0 in range(q):
    m.append(int(input().strip()))

for i in range (0, k % n):
    temp = a[n-1]    # Stores the last element temporarily
    a.pop(n-1)       # Removes the last element
    a = [temp] + a   # Appends the temporary element to the start (prepends)


for i in range (0, q):
    print(a[m[i]])
</code></pre>

<p>There's no need to transform the list at all. Just subtract <code>k</code> from the index you're passed whenever you do a lookup (perhaps with a modulus if <code>k</code> could be larger than <code>n</code>). This is <code>O(1)</code> per lookup, or <code>O(q)</code> overall.</p>

<p>Even if you wanted to transform the actual list, there's no need to do it one element at a time (which will require <code>k</code> operations that each take <code>O(n)</code> time, so <code>O(n*k)</code> total). You can simply concatenate <code>a[-k:]</code> and <code>a[:-k]</code> (again, perhaps with a modulus to fix the <code>k &gt; n</code> case), taking <code>O(n)</code> time just once.</p>

python python-3.x