Cyclically Rotate an Array by One easy
Description
Given an array, cyclically rotate the array clockwise by one position. The last element moves to the front, and all other elements shift right by one.
Examples
> Case 1:
Input: arr = [1, 2, 3, 4, 5]
Output: [5, 1, 2, 3, 4]
> Case 2:
Input: arr = [9, 8, 7, 6, 4, 2, 1, 3]
Output: [3, 9, 8, 7, 6, 4, 2, 1]Constraints
1 <= arr.length <= 10^5
Approach
- Store the last element
- Shift all elements right by one position
- Place the stored element at the front
Cyclic Rotation of [1, 2, 3, 4, 5]
Step 1 of 6
1
[0]2
[1]3
[2]4
[3]5
[4]Step 1: Save the last element (5).
Code
Explanation
- We save the last element since it will be overwritten during the shift
- We iterate from right to left, moving each element one position to the right
- Finally, we place the saved last element at position 0
- The Python slicing approach
[arr[-1]] + arr[:-1]is cleaner but creates a new list (O(n) space)
Analysis
- Time Complexity:
O(n)— shift all n elements - Space Complexity:
O(1)— in-place with one temp variable