We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Obviously this solves the problem, but is a terrible solution. Pop is an O(N) operation. So your solution becomes O(K*N). This should be done in O(N) total time complexity. You do have the space requirement of O(1) correct. All the standard solutions have a O(N) space complexity.

True. However, it becomes an elegant solution if we use collections.dequeue instead of list. Double ended queues have a popleft method, which is an O(1) operation:

And array_left_rotation only takes O(k) instead of O(n).

Note that a is pased by reference, so there is no need to return anything, but this could be an issue for some user cases, for this particular problem, it works.

## Arrays: Left Rotation

You are viewing a single comment's thread. Return to all comments →

Yeah index slicing FTW, here was my 1-liner in definition, lol:

is that scala?

It's Python 3

you dont need to pass n to your function, right..

I agree - I ended up not using 'n' (Python):

Obviously this solves the problem, but is a terrible solution. Pop is an O(N) operation. So your solution becomes O(K*N). This should be done in O(N) total time complexity. You do have the space requirement of O(1) correct. All the standard solutions have a O(N) space complexity.

True. However, it becomes an elegant solution if we use collections.dequeue instead of list. Double ended queues have a popleft method, which is an O(1) operation:

More info: https://wiki.python.org/moin/TimeComplexity#collections.deque https://docs.python.org/3/library/collections.html#collections.deque

They have rotate built into the deque

You have O(n) in:

In order to avoid this, you should use a deque from the beginning like:

And

array_left_rotationonly takes O(k) instead of O(n).Note that

ais pased by reference, so there is no need to return anything, but this could be an issue for some user cases, for this particular problem, it works.i'd change '''for _ in range(k%len(a)) ''' to be more eficent

def array_left_rotation(a, n, k): return (a[k:] + a[:k])

`k -> k%n`

k%n handles any range of shifts, but the problem specifies n < k so you can just use k in this case

This logic fails when k>n.

for that, do:

Nice, only one line was added

Perfection. Short, simple, & clean.

hmm nice....

It's so smart! well done:)

Can you please explain how (a[k:]+a[:k]) is working?

Damn this is super impressive.