My code works fine, but it's takes too much time, say around 65 seconds, for large input data. If there are 50,000 numbers in the list \$a\$ and we have to rotate the numbers 45,000 times then it takes 1 minute.
How can I reduce the time it takes to print all the numbers?
Problem:
perform an operation called a right circular rotation on an array of integers [a0 , a1 , a2 , ..a(n-1)]
. After performing one right circular rotation operation, the array is transformed to [a(n-1) , a0 , a1 ,..a(n-2)]
.
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\$.
n,k,q = input().strip().split(' ') #n=no of integers in the list , k=no of rotation ,q=no of lines for integer m
n,k,q = [int(n),int(k),int(q)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
for i in range(0,k):
a=[a.pop(n-1)]+a #for putting the last element to the first position and del it from the last pos
for a0 in range(q): # printing value of a at a given index
m = int(input().strip())
print(a[m])
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 \$2\$ on a new line.
- \$m=1\$, so we print \$3\$ on a new line.
- \$m=2\$, so we print \$1\$ on a new line.