user10418143
user10418143

Reputation: 352

What is the Efficient way to right rotate list circularly in python without inbuilt function

def circularArrayRotation(a, k, queries):
    temp=a+a
    indexToCountFrom=len(a)-k

    for val in queries:
       print(temp[indexToCountFrom+val])

I am having this code to perform the rotation .

This function takes list as a, the number of time it needs to be rotated as k, and last is query which is a list containing indices whose value is needed after the all rotation.

My code works for all the cases except some bigger ones.

Where i am doing it wrong ?

link: https://www.hackerrank.com/challenges/circular-array-rotation/problem

Upvotes: 0

Views: 352

Answers (1)

trincot
trincot

Reputation: 350705

You'll probably run into a timeout when you concatenate large lists with temp = a + a.

Instead, don't create a new list, but use the modulo operator in your loop:

   print(a[(indexToCountFrom+val) % len(a)])

Upvotes: 1

Related Questions