Technology

Rotating an Array Left by One in JavaScript

Beginner 5 min read VisTechie Team Technology
1 views

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
1 views

Comments

0/2000

Comments are reviewed before being published.

Loading comments...

Related Articles