#189

Rotate Array

Medium Reversal trick

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Rotate an array to the right by k steps in place.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: shift every element k steps to the right, wrapping around.

Why this works: rotating = moving the last k elements to the front. Reversing everything, then reversing the two parts, achieves exactly that with no extra array.

Example: [1, 2, 3, 4, 5, 6, 7], k = 3

reverse all:   7 6 5 4 3 2 1reverse first 3: 5 6 7 4 3 2 1reverse rest:  5 6 7 1 2 3 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Shifting one step at a time k times — O(n·k), which times out.