Explain array rotation.
Skip to solutionKEEP THE
mediumDSA
How do you rotate an array by k positions?
881 views
01
Understand the problem
arraysrotation
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
The reversal trick: reverse the whole array, then reverse the first k and the remaining n−k. This rotates in O(n) time, O(1) space, avoiding extra arrays or repeated single-step shifts.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Reversal method (O(1) space)
Run Playgrounddef rotate(nums, k):
n = len(nums)
k %= n
def reverse(lo, hi):
while lo < hi:
nums[lo], nums[hi] = nums[hi], nums[lo]
lo += 1; hi -= 1
reverse(0, n - 1)
reverse(0, k - 1)
reverse(k, n - 1)
return nums
# --- demo ---
print(rotate([1, 2, 3, 4, 5], 2)) # [4, 5, 1, 2, 3]05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 42 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.