hi, let Avik connect you.
** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.
** You can check all the posts on the Posts page.
** More about me in the About Me section.
Left Rotate an Array by One
Problem: Left Rotate an Array by One
Problem Link: www.codingninjas.com/codestudio/problems/left-rotate-an-array-by-one_5026278
Companies Asked: Wipro
Approach:
Traverse through the array.
Assign the 0'th element to a variable say, first.
For the rest of the i, from 1 to N, put ith element to (i - 1)th position.
Assign first to (N - 1)st position.
Return the resultant array.
Time and Space Complexity:
Time Complexity: O(N)
Space Complexity: O(1)
Code [C++]
#include <bits/stdc++.h>
vector<int> rotateArray(vector<int>& arr, int n) {
int first = arr[0];
for(int i=0; i<n-1; i++){
arr[i] = arr[i+1];
}
arr[n-1] = first;
return arr;
}