Reputation: 1
I tried to left rotate the array in python by giving the number of rotation I wanted but I'am unable to find the mistake in it It's perfectly working when I'm trying on jupyter IDE but HackerRank platform is showing wrong answer my code:
def rotateLeft(d, arr):
for i in range(d):
temp=arr[0]
for j in range(len(arr)-1):
arr[i]=arr[i+1]
arr[len(arr)-1]=temp
return arr
The question
For example
input:
5 4
1 2 3 4 5
my output:
2 3 4 2 2
which is wrong. Where is the error?
Upvotes: 0
Views: 306
Reputation: 1573
The update in the inner loop should use j
instead of i
. This should work
def rotateLeft(d, arr):
for i in range(d):
temp=arr[0]
for j in range(len(arr)-1):
arr[j]=arr[j+1]
arr[len(arr)-1]=temp
return arr
However, there are simpler solutions to the question. For example the previous answer here.
Upvotes: 0
Reputation: 160
The solution is easier than you think, have you tried just cuting the array in two parts and concatenate inverting parts again.?
ex> [1,2,3,4] 2 rotate: [3,4] + [1,2]
result : 3,4,1,2
In python is so easy to do this.
def rotateLeft(d, arr):
return arr[d:] + arr[0:d]
This solution have a bug, when the number of rotations are greater than length of the array wont do nothing, so if you calculate the mod of d you can pass it any number.
def rotateLeft(d, arr):
d = d % len(arr)
return arr[d:] + arr[0:d]
Upvotes: 1