Rotating a Sequence by an Offset

A rotation changes the front of a sequence while preserving its cyclic order. Normalize the offset before splitting.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a left rotation
  2. Express the join of two spans
  3. Reduce a shift modulo the length
  4. Check that no elements are shifted out of existence

Trace a left rotation

Rotating A, B, C, D left two places yields C, D, A, B. A positive left offset six has the same effect because six leaves remainder two by four. Quotient and remainder handle oversized offsets.

Express the join of two spans

Use the suffix from the normalized offset followed by the prefix before it. The half-open slice rule arranges the split without losing a value. For an empty input, handle the case before taking a remainder with divisor zero.[1]

Reduce a shift modulo the length

Rotating [A, B, C, D, E] left by seven is equivalent to rotating left by two, because one complete lap returns to the starting order. The result is [C, D, E, A, B]. For nonempty length \(n\), the item at result position \(j\) came from source position \((j+k)\bmod n\) for a left rotation by \(k\). Decide how your API describes signed shifts and direction. See quotient and remainder.

Check that no elements are shifted out of existence

A move by two shifts two items around the boundary. A simple suffix discards them. Compare the input and output counts, and test that applying left rotations by \(k\) and then by \(-k\) reconstructs the original. Include a shift by zero, a shift equal to the length, a singleton and an empty input. Handle empty input before computing a remainder modulo the length. See sequence slice boundaries.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩