Today's LeetCode challenge taught me the power of the modulo operator and how mathematical insights can turn a seemingly complex problem into an elegant solution. The real "aha" moment came when I started thinking about array rotation as a circular motion rather than linear movement.
The Challenge
Given an array nums
and an integer k
, rotate the array to the right by k
steps. For example:
javascriptCopyInput: nums = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
My Initial Approach
Like many developers, I first thought about shifting elements one by one:
Move last element to front
Repeat k times This would work, but felt clunky and inefficient. That's when I started thinking about position mapping.
The Breakthrough
The key insight came when visualizing the array as a circle:
In a circle of size 5, moving 7 spaces = moving 2 spaces
Moving any number of steps can be simplified using modulo
Each element's new position = (current position + k) % array length
What would assist in this is the modulo operator; which would naturally handle the wrapping for us:
If k = 7 and array length = 5:
Position 0 → (0 + 7) % 5 = 2
Position 1 → (1 + 7) % 5 = 3
Position 2 → (2 + 7) % 5 = 4
Position 3 → (3 + 7) % 5 = 0
Position 4 → (4 + 7) % 5 = 1
The Solution: Simple and to the Point
javascriptCopyvar rotate = function(nums, k) {
const temp = [...nums];
for (let i = 0; i < nums.length; i++) {
const newPosition = (i + k) % nums.length;
nums[newPosition] = temp[i];
}
};
Why It Works
Let's break it down:
The temp array preserves original values while we modify
The modulo operator handles "wrapping" around array end
Each element moves exactly k positions (after wrapping)
New positions are calculated relative to original positions
Learning Impact
This problem taught me several valuable lessons about array wrapping:
Understanding Array Boundaries: I learned that when you need to move beyond an array's length, modulo naturally handles the wrapping. Just like a clock moving from 12 back to 1, an array can wrap from its last index back to 0.
Position Mapping Made Simple: The formula
(current + k) % length
maps old positions to new ones, no matter how large k becomes. This simple math eliminates the need for complex boundary checking.The Power of Index Arithmetic: Array rotations aren't about moving elements one by one - they're about calculating where each element belongs. Understanding this transformed my approach to array manipulation.
Circular Motion in Linear Structures: While arrays are linear in memory, they can behave circularly through clever index manipulation. This concept opens up new ways to think about array operations.
Most importantly, this challenge showed me that understanding array wrapping isn't just about avoiding "Index out of bounds" errors - it's about seeing arrays as flexible structures that can handle circular operations naturally.