Problem Statement
Given an array of n
integers, left rotate the array by one place.
Examples
Example 1:
Input: nums = [4, 5, 6, 7]
Output: [5, 6, 7, 4]
Explanation: The array is rotated left by 1. Thus causing element at index 0 to be placed at last index.
Example 2:
Input: nums = [-1, 0, 2, 5, 8]
Output: [0, 2, 5, 8, -1]
Explanation: The array is rotated left by 1. Thus causing element at index 0 to be placed at last index.
Different Approaches
1️⃣ Traversal Approach
Intuition:
To rotate an array by one position to the left, consider that the first element of the array will move to the last position, while all other elements shift one position to the left. The thought process involves first capturing the value of the first element in a temporary variable. Next, iterate through the array starting from the second element and shift each element to the position of its predecessor. Finally, place the initially captured value into the last position of the array. This approach ensures that the array is rotated by one position effectively.
Approach:
- Store the value of the first element of the array in a temporary variable.
- Iterate through the array starting from the second element.
- Shift each element one position to the left by assigning the current element to the position of its predecessor.
- After completing the iteration, place the value from the temporary variable into the last position of the array.
Algorithm:
- Store the first element of the array in a temporary variable.
- Shift all other elements one position to the left.
- Place the temporary variable (containing the first element) at the end of the array.
Code:
#include <iostream>
using namespace std;
void leftRotateByOne(int arr[], int n) {
// Store the first element
int temp = arr[0];
// Shift elements to the left
for (int i = 1; i < n; ++i) {
arr[i - 1] = arr[i];
}
arr[n - 1] = temp;
}
int main() {
int arr[] = {3, 7, 1, 9, 4};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Original Array: ";
for (int i = 0; i < size; ++i)
cout << arr[i] << " ";
cout << endl;
leftRotateByOne(arr, size);
cout << "Array after left rotation: ";
for (int i = 0; i < size; ++i)
cout << arr[i] << " ";
cout << endl;
return 0;
}
// Output
Original Array: 3 7 1 9 4
Array after left rotation: 7 1 9 4 3
OR Using Vector:
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
void rotateArrayByOne(vector<int>& nums) {
// Store the first element in a temporary variable
int temp = nums[0];
// Shift elements to the left
for (int i = 1; i < nums.size(); ++i) {
nums[i - 1] = nums[i];
}
// Place the first element at the end
nums[nums.size() - 1] = temp;
}
};
int main() {
Solution solution;
vector<int> nums = {1, 2, 3, 4, 5};
solution.rotateArrayByOne(nums);
for (int num : nums) {
cout << num << " "; // Output the rotated array
}
return 0;
}
Complexity Analysis
- Time Complexity:
O(N)
, whereN
is the number of elements in the array. - Space Complexity:
O(1)