Left Rotate Array by One
EasySave the first, shift left, put it back
Problem
Given an integer array nums, rotate the array to the left by one. Note: There is no need to return anything, just modify the given array.
Save the first element, shift everyone left, then drop the saved one at the end.
The idea
Stash nums[0], shift every later element one place left, and drop the saved value at the end. Saving first is essential — overwriting nums[0] before reading it loses the element you need.
The trick
- One temporary variable is all the extra space required.
- Rotating right by one is the same routine run backwards.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — nums = [1, 2, 3, 4, 5] Values: 1, 2, 3, 4, 5.
1first = nums[0]2for i in 1..n-1: nums[i-1] = nums[i]3nums[n-1] = firstInput
- array
- [1, 2, 3, 4, 5]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- nums = [1, 2, 3, 4, 5]
- Output:
- [2, 3, 4, 5, 1]
- Explanation:
- The first element wraps around to the end.
Example 2
- Input:
- nums = [7, 8]
- Output:
- [8, 7]
- Explanation:
- Two elements just swap.
Example 3
- Input:
- nums = [9]
- Output:
- [9]
- Explanation:
- One element stays put.
Constraints
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.