Problem: Circular Array Rotation | HackerRank
Can anyone tell why the below code for the problem shows run time error
a, k, q = list(map(int, input().split()))
lis = list(map(int, input().split()))
r=[]
for e in range(q):
r.append(int(input()))
lis1 = list(lis)
for i in range(k):
a1=list(lis)
a1[0]=lis1[-1]
for j in range(1,len(lis)):
a1[j]=lis1[j-1]
lis1=a1
for items in r:
print(lis1[items])
There is a simple logic to solve the problem, you are just doing too much copy of memory and I don’t understand why/what are you doing in the following:
for i in range(k):
a1=list(lis)
a1[0]=lis1[-1]
for j in range(1,len(lis)):
a1[j]=lis1[j-1]
lis1=a1
Refer to the below code for a simple solution:
def main():
n, k, q = tuple(map(int, input().strip().split()))
read_sequence = list(map(int, input().strip().split()))
rotated_sequence = [0] * n
for index, data in enumerate(read_sequence):
rotated_sequence[(index + k) % n] = data
for _ in range(q):
print(f"{rotated_sequence[int(input().strip())]}")
if __name__ == "__main__":
main()