Pattern visualizer
Rotate Array
Rotating right by k moves the last k values to the front and slides the rest back. The obvious fix is a copy, but that costs O(n) memory, and shifting one step at a time k times costs O(n*k). Reversing the whole array gets the tail to the front in one pass — it just leaves both halves backwards. Reversing each half separately straightens them out, so three linear reversals do the whole rotation in place. Animated on: nums = [1,2,3,4,5,6,7], k = 3 — rotate the array right by k steps, in place..
Three reversals rotate in place
Rotating right by k=3 means the last 3 values [5, 6, 7] must end up at the front. Copying them aside would cost O(n) extra memory, so instead the whole row gets reversed and then un-reversed in two pieces.
1FUNCTION rotate(nums, k):2 n <- LENGTH(nums)3 k <- k MOD n4 REVERSE(nums, 0, n - 1)5 REVERSE(nums, 0, k - 1)6 REVERSE(nums, k, n - 1)7 RETURN nums8FUNCTION REVERSE(A, l, r):9 WHILE l < r:10 SWAP A[l] AND A[r]11 l <- l + 112 r <- r - 1
← / → step · space play · Home restart