[Python] Left Rotation on an Array

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    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
    a = 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?

    Continue reading...

Compartilhe esta Página