19 / 19

How do you rotate an array by k positions? (In-place vs extra space)

Difficulty: 3/10

Array Rotation

For right rotation by k positions, first reduce k using k modulo n. An efficient in-place approach uses three reversals: reverse the entire array, reverse the first k elements, then reverse the remaining elements.

javascript
  1. 1

    Time complexity: O(n).

  2. 2

    Extra space: O(1) for the reversal approach.

  3. 3

    An extra-array approach is simpler but requires O(n) additional space.

  4. 4

    For very large k, k % n avoids unnecessary rotations.

  5. 5

    The direction of rotation must be defined clearly.

Follow-up Questions

  • How would you rotate left by k?
  • Can you solve rotation using the cyclic replacement method?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.