Given an integer array nums, your task is to rotate it to the right by k positions, where k is a non-negative integer.
Example
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]Solution
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function (nums, k) {
let steps = k % nums.length;
if (nums.length == 1) {
return nums;
}
reverseArrayFromItoJ(nums, 0, nums.length - 1)
reverseArrayFromItoJ(nums, 0, steps - 1)
reverseArrayFromItoJ(nums, steps, nums.length - 1)
return nums;
};
var reverseArrayFromItoJ = function (nums, i, j) {
while (i < j) {
let temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
i++;
j--;
}
return nums;
}🧠 Key Learnings
From the Rotate Array problem, I learned how to use the reverse technique with two pointers to perform array rotation efficiently in-place. This approach deepened my understanding of modular arithmetic for handling cyclic shifts and how complex transformations can be broken down into simpler reversible steps. The pattern of reversing subarrays is highly reusable in problems involving string or linked list reversal, palindrome checks, and cyclic data structures.
1. In-place reversal logic (two-pointer swap)
- The helper function
reverseArrayFromItoJ()uses the two-pointer approach. - You move one pointer from the start (
i) and one from the end (j), swapping until they meet. - This technique allows reversing any subarray in O(n) time and O(1) space.
- 🔁 Reusable pattern — this two-pointer reversal is a building block in:
- Reversing linked lists.
- Reversing strings or sub-strings.
- Palindrome checks.
- Sliding window adjustments.
- Array rearrangements.
2. Modular arithmetic for rotation
let steps = k % nums.length;
- Using
%ensures thatkvalues larger than array length wrap around correctly. - This modular thinking applies to cyclic problems like:
- Rotating matrices or linked lists.
- Circular queues.
- “Clockwise rotation” or “wrap-around indexing” logic.
3. Breaking a big transformation into smaller reversals
The rotation logic works because:
Rotate Right by k steps =
Reverse entire array +
Reverse first k +
Reverse remaining n - k
👉 This decomposition trick is powerful.
It shows how a complex rearrangement can be reduced to smaller, reversible segments — a useful mindset for:
- String rotations.
- Matrix layer rotations.
- Segment-based array manipulations.
4. In-place modification (no extra array)
- This problem teaches memory-efficient thinking.
- By manipulating indices cleverly, we avoid using extra arrays.
- Important in interviews where the question says:
“Modify the input array in-place.”
5. Reusability and Modularity
- The helper function
reverseArrayFromItoJ()is generic and reusable. - This modular design helps clean up logic and avoids duplication — a good coding practice for:
- Sorting subarrays.
- Partitioning logic in quicksort.
- Reversing ranges in string or array manipulation problems.

