Home > front end >  Rotate Left k cells where k is greater than the length of the array
Rotate Left k cells where k is greater than the length of the array

Time:10-05

If the length of the given array is 6 and the value of k is 7 then the resultant array should be like this [20, 30, 40, 50, 60, 10]. My work.

source = [10, 20, 30, 40, 50, 60]
def rotateLeft(array, k):
    tempArray = [0] * len(array)
    flag = k
    j = len(array)
    temp = k - len(array) - 1
    temp2 = len(array) - 1
    for i in range(j):
        tempArray[i] = source[i]
        if i   k < j:
            source[i] = source[i   k]
            source[flag] = tempArray[i]
            flag  = 1
        //Before this everything is alright.
        elif k > len(array):
            while temp2 >= temp:
                source[temp2] = source[temp2 - temp]
                temp2 -= 1
    print(source)


rotateLeft(source, 7)

Output is [10, 20, 30, 40, 50, 60]. Expected [20, 30, 40, 50, 60, 10]. Can anyone help!!Thank you.

CodePudding user response:

How about using modulus dividion

k=k%len(array)

This would make it that is the number of places that the array needs to move by. Since after this operation 0 <= K < len(array) you can shift the array with

array = array[k:]   array [:k]
  • Related