Left Rotate Array by One
Problem
Given an integer array arr of size n, rotate it left by one position in place: the first element moves to the end and every other element shifts one index to the left.
Input / Output
- Input: integer array
arr. - Output: the rotated array.
Examples
Example 1
Input: arr = [1, 2, 3, 4, 5]
Output: [2, 3, 4, 5, 1]
Example 2
Input: arr = [7]
Output: [7]
Example 3
Input: arr = [4, 9]
Output: [9, 4]
Constraints
1 <= n <= 10^5
Approach
- Save
first = arr[0]. - For
ifrom 1 ton-1, setarr[i-1] = arr[i]. - Set
arr[n-1] = first.
Each element is moved exactly once, so the cost is linear with constant extra memory. Building a new array arr[1:] + arr[:1] is simpler but uses O(n) additional space, which the interviewer will point out.
This problem is the warm-up for rotate by k, which generalises the idea: either repeat the single rotation k times (O(n·k), bad), or use the three-reversal trick (reverse the first k, reverse the rest, reverse everything) for O(n) time and O(1) space.
Complexity
- Time: O(n)
- Space: O(1)
Reference solution (Python)
def left_rotate_by_one(arr):
if len(arr) <= 1:
return arr
first = arr[0]
for i in range(1, len(arr)):
arr[i - 1] = arr[i]
arr[-1] = first
return arr
Test cases
| Input | Expected |
|---|---|
[1,2,3,4,5] | [2,3,4,5,1] |
[7] | [7] |
[4,9] | [9,4] |
[1,1,2] | [1,2,1] |