Arrays: Left Rotation

Fermin Blanco
2 min readAug 24, 2023

--

Slice left rotation

Problem statement

A left rotation operation on an Slice shifts each elements o the slice 1 position to the left, and the one who is at first place will be colocated on the last position and so on.

Slice left rotation problem statement

Considerations

Given the signature of our function:

Function signature

We need to be carefull with one detail, if d the number of left rotation to be performed is greater than len(a) the length of the slice. Our following operation will panic. panic: runtime error: slice bounds out of range [:d] with capacity cap

Panic: Slice out of range

Hopefully we can recalculate the number of positions we need to slice in order to rotate the array without panic.

The mod operator

Using the mod operator

The mod operator works in the following way, no matter how big the numbers of rotations will be it always fall into a shift of positions on the Slice. For instance for an [1 2 3 4 5]Slice of len(5) it will be same to rotate it 6positions instead of 11 or 16 because it turns out that for an Slice of this length it will always comes to rotate just1 position. And how come will array to this number?

Mod operator explanation

The algorithm

  1. The function checks if d is greater than the length of the array a. If it is, then the function calculates the modulus of d and uses that value as the actual rotation to be performed.
  2. The function slices the array a at the dth position. The first slice, left, contains the first d elements of the array. The second slice, right, contains the remaining elements of the array.
  3. The function joins the two slices together, starting with the right slice and then appending the reversed left slice.
Slice left rotation

Resources

I ask Google Bard to explain my code.

--

--

Fermin Blanco
Fermin Blanco

Written by Fermin Blanco

I write to fill my gaps not to show yours.

No responses yet