Rotate the array to the left by one position.
Problem Statement
Given an array of integers, left rotate the array by one position.
Examples
Input: arr = [1, 2, 3, 4, 5]
Output: [2, 3, 4, 5, 1]
Explanation: First element moved to the end.
Constraints
Standard constraints
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Left rotating by one means moving arr[0] to the end and shifting all other elements one position to the left.
š” Hint 2:
Store arr[0] in a temporary variable first.
š” Hint 3:
Shift arr[i] = arr[i + 1] for i = 0 to length - 2, then set arr[length - 1] = first.
Editorial & Approach
Problem Overview & Intuition
In left rotation by one place, the first element cycles to the end, while every other element moves one index to the left (i -> i - 1). This is done in-place with a temporary variable storing the first element.
Step-by-Step Approach
- If
arr.length <= 1, returnarrimmediately. - Store the first element:
const first = arr[0];. - Iterate from
i = 0toarr.length - 2, settingarr[i] = arr[i + 1]. - Set
arr[arr.length - 1] = first. - Return
arr.
Optimal Implementation (JavaScript)
function leftRotateByOne(arr) {
if (arr.length <= 1) return arr;
const first = arr[0];
for (let i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.length - 1] = first;
return arr;
}
Complexity Analysis
Time Complexity
O(N) ā single pass shifting N - 1 elements.
Space Complexity
O(1) ā in-place rotation using a single temporary variable.
Edge Cases & Corner Traps Handled
- Single element array: remains unchanged.
- Two elements: swaps position.
- Negative and duplicate values handled transparently.