Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left Rotation on an Array

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?

like image 610
mourinho Avatar asked Mar 24 '18 07:03

mourinho


People also ask

How do you left rotate an array?

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.

How do you rotate an array to the left in Java?

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.

What is meant by left rotation?

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.

How do you rotate an array left and right by a given number K?

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.


2 Answers

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)]
like image 183
Sreeram TP Avatar answered Oct 01 '22 13:10

Sreeram TP


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

like image 41
Ken Mbogo Avatar answered Oct 01 '22 11:10

Ken Mbogo