0

I am trying to implement a circular rotation algorithm for a hackerrank challenge question. My code(middle block) seems to run fine for small inputs but fails for larger inputs due to timeout. Any help optimizing the code will be much appreciated.

Here is my code:

import sys


n,k,q = raw_input().strip().split(' ')
n,k,q = [int(n),int(k),int(q)]
a = map(int,raw_input().strip().split(' '))

for j in range(0,k):
    temp = a[n-1]
    for i in range(n-2, -1, -1):
        a[i+1] = a[i]
    a[0] = temp    


for a0 in xrange(q):
    m = int(raw_input().strip())
    print a[m]
1
  • Consider using numpy. Commented Sep 6, 2017 at 3:43

1 Answer 1

1

You don't have to actually rotate the array to find the item but you can use modulo calculus to do that. If we have index i and we move it k places his new index will be m=(i+k)%n so if we have an index m that has been moved k places then it's previous location was i=(m-k)%n, but since we have to handle it becoming negative if k > m we add len(a), python handles this but in general it's the more complete answer.

Knowing that we can write the following:

for a0 in xrange(q):
    m = int(raw_input().strip())
    prev_index = (len(a) + m - k) % n
    print a[prev_index]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.