Rotate Array by k Steps - Three Approaches

by linkjobai

HTML

<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Rotate Array by k Steps: Three Approaches and the Reversal Trick</title><style>body{max-width:720px;margin:40px auto;font-family:system-ui,sans-serif;line-height:1.6;padding:0 16px}</style></head><body>
<h1>Rotate Array by k Steps: Three Approaches and the Reversal Trick</h1>
<p>Rotate Array asks you to shift every element of an array k steps to the right. It looks trivial, but interviewers use it to see whether you can move from an extra-array solution to an in-place one.</p>
<p>First, reduce k with k = k % n, because rotating by n leaves the array unchanged. Forgetting this is the most common bug.</p>
<p>Approach one: copy into a new array where new[(i + k) % n] = a[i]. O(n) time, O(n) space, easy to get right.</p>
<p>Approach two, the reversal trick: reverse the whole array, then reverse the first k elements, then reverse the remaining n - k elements. O(n) time and O(1) space. For [1,2,3,4,5,6,7] with k = 3: reverse all gives [7,6,5,4,3,2,1], reverse first three gives [5,6,7,4,3,2,1], reverse the rest gives [5,6,7,1,2,3,4].</p>
<p>Approach three, cyclic replacements: move each element to its final slot and follow the cycle; the number of cycles is gcd(n, k). It is also O(1) space but harder to explain under pressure.</p>
<p>Interview tips: lead with the copy approach, then offer the reversal trick and prove it on a seven-element example. Mention that left rotation is the same idea with the reversals in a different order.</p>
<p>Disclosure: I work on Linkjob AI. If you want to rehearse problems like this with live hints, <a href="https://www.linkjob.ai/">www.linkjob.ai</a> can help you practice explaining your approach.</p>
</body></html>