Question -
Find element at given index after a number of rotations.
Example -
Input : arr[] ={1,2,3,4,5} , range[] = {{0,2}, {0,3}} , index = 1
Output : 3
Approach -
we rotate the array with specified element and atleast we print value of arr[index].
Implementation -
#include<iostream>
using namespace std;
void rotate(int arr[],int start,int end)
{
int temp=arr[start];
for(int i=0;i<end-1;i++)
arr[i]=arr[i+1];
arr[end-1]=temp;
}
void findelement(int arr[],int rotations,int index,int range[][2],int n)
{
for(int i=0;i<rotations;i++){
rotate(arr,range[i][0],range[i][1]);
}
cout<<"After rotation value at index is : "<<arr[index]<<endl;
}
int main()
{
int n;
cout<<"Enter number of element : ";cin>>n;
int arr[n];
cout<<"Enter elements : "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
int rotations;
cout<<"Enter number of rotation : ";cin>>rotations;
int range[rotations][2];
cout<<"Enter rotations range : "<<endl;
for(int i=0;i<rotations;i++){
cout<<"Range "<<i+1<<" : ";
cin>>range[i][0];
cin>>range[i][1];
}
int index;
cout<<"Enter index : ";cin>>index;
findelement(arr,rotations,index,range,n);
}
Time complexity - O(n*n)
Space - O(n)
Comments
Post a Comment