Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Left Rotate an Array by D places #58

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions LeftRotationDplace(Better).cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Left Rotate an Array by d places
// example:
// Input: arr[] = {1, 2, 3, 4, 5, 6, 7}
// d = 2
// Output: arr[] = {3, 4, 5, 6, 7, 1, 2}

#include<bits/stdc++.h>
using namespace std;
#define vi vector<int>

// Efficient Solution
// Time Complexity: O(n)
// Space Complexity: O(d)

signed main(){
int n,d;
cin>>n>>d;
vi v(n);
for(int i=0;i<n;i++)
cin>>v[i];

// Efficient Approach
int temp[d];
for(int i=0;i<d;i++)
temp[i]=v[i];

for(int i=d;i<n;i++)
v[i-d]=v[i];

for(int i=0;i<d;i++)
v[n-d+i]=temp[i];

for(int i=0;i<n;i++)
cout<<v[i]<<" ";
return 0;
}
35 changes: 35 additions & 0 deletions LeftRotationDplace(Efficient).cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Left Rotate an Array by D places
// example:
// Input: arr[] = {1, 2, 3, 4, 5, 6, 7}
// d = 2
// Output: arr[] = {3, 4, 5, 6, 7, 1, 2}

#include<bits/stdc++.h>
using namespace std;
#define vi vector<int>

// Optimal Solution
// Time Complexity: O(n)
// Space Complexity: O(1)

signed main(){
int n,d;
cin>>n>>d;
vi v(n);
for(int i=0;i<n;i++)
cin>>v[i];
// More Efficient Approach
// Reversal Approach
// 1. Reverse the first d elements
// 2. Reverse the last n-d elements
// 3. Reverse the whole array

reverse(v.begin(),v.begin()+d);
reverse(v.begin()+d,v.end());
reverse(v.begin(),v.end());

for(int i=0;i<n;i++)
cout<<v[i]<<" ";
return 0;
}

39 changes: 39 additions & 0 deletions LeftRotationDplace(Naive).cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Left Rotate an Array by D places
// example:
// Input: arr[] = {1, 2, 3, 4, 5, 6, 7}
// d = 2
// Output: arr[] = {3, 4, 5, 6, 7, 1, 2}

#include<bits/stdc++.h>
using namespace std;
#define vi vector<int>

// naive solution
// Time Complexity: O(n*d)
// Space Complexity: O(1)

signed main(){
int n,d;
cin>>n>>d;
vi v(n);/
for(int i=0;i<n;i++)
cin>>v[i];

// Naive Approach
while(d--)
{
for(int i = 0; i < n-1; i++)
{
swap(v[i],v[i+1]);
}
}

for(int i=0;i<n;i++)
cout<<v[i]<<" ";
return 0;
}