I have a question where I need to rotate an array left k times.
i.e. if k = 2, [1, 2, 3, 4, 5] . -> [3, 4, 5, 1, 2]
So, my code is:
def array_left_rotation(a, n, k):
for i in range(n):
t = a[i]
a[i] = a[(i+n-1+k)%n]
a[(i+n-1+k)%n] = t
return a
where n = length of the array.
I think the problem is a mapping problem, a[0] -> a[n-1] if k = 1.
What is wrong with my solution?
The array can be left rotated by shifting its elements to a position prior to them which can be accomplished by looping through the array and perform the operation arr[j] = arr[j+1]. The first element of the array will be added to the last of rotated array.
if you are using List(not array) use the inbuilt function Collections. rotate(+ve no) to rotate right and Collections. rotate(-ve no) to rotate left.
Left rotation refers to the following. In an array, moving all items to the next lower location. The first item is moved to the last location, which is now vacant. In a list, removing the head and inserting it at the tail.
To rotate by one, store arr[N] in a temporary variable temp, move arr[N-1] to arr[N], arr[N-2] to arr[N-1] … and finally temp to arr[1]. We get [5, 1, 2, 3, 4] after first rotation and [ 4, 5, 1, 2, 3] after second rotation.
Another way to do this with the help of indexing is shown below..
def rotate(l, n):
return l[n:] + l[:n]
print(rotate([1, 2, 3, 4, 5], 2))
#output : [3, 4, 5, 1, 2]
This will only return the original list if n is outside the range [-len(l), len(l)]
. To make it work for all values of n, use:
def rotate(l, n):
return l[-n % len(l):] + l[:-n % len(l)]
def leftRotation(a, d, n):
i=0
while i < n:
print (a[(i+d)%n], end = ' ')
i+=1
return i
if __name__ == '__main__':
a =[1, 2, 3, 4, 5, 6, 7]
d = 4
n = 7 or len(a)
leftRotation(a, d, n)
This is how I solved my hackerrank left rotation challenge
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With