What "left rotate by one" means
Every element shifts one spot to the left, and whatever was first wraps around to become last. So [1, 2, 3, 4, 5] turns into [2, 3, 4, 5, 1].
The approach
Grab the first element and hold onto it, shift everything else left by one using a loop, then drop the saved value into the final slot.
function leftRotateByOne(arr) {
const first = arr[0];
const len = arr.length;
for (let i = 0; i < len - 1; i++) {
arr[i] = arr[i + 1];
}
arr[len - 1] = first;
}
const nums = [1, 2, 3, 4, 5];
leftRotateByOne(nums);
console.log(nums); // [2, 3, 4, 5, 1]
Why the loop stops at len - 1
The loop only runs up to, but not including, len - 1. Push it further and the last assignment reads arr[len], which is undefined - you'd end up overwriting the last real value with nothing.
Complexity, quickly
- Time: O(n), a single pass through the array
- Space: O(1), just one extra variable no matter how big the array gets
Comments
Loading comments...
Related Articles
Taming Slow MongoDB Aggregation Pipelines in Production
An aggregation pipeline that returns instantly on your 500-document local dataset can crawl once it hits a few million real documents. Here's how to actually find and fix the stage that's costing you.
Read ArticleBuilding a Sliding-Window Rate Limiter for Node.js APIs with Redis
Fixed-window rate limiting looks fine in a demo and then lets through double the traffic right at the window boundary. Here's the sliding-window-counter approach that fixes that, built directly on Redis.
Read ArticleMulti-Tenant Data Isolation: Shared Schema vs Separate Databases
Every multi-tenant SaaS eventually has to answer one question honestly: how do you stop one customer from ever seeing another customer's data? Here's how the three common isolation strategies actually compare in practice.
Read Article