Question -
An array consisting of N integers is given. There are several Right Circular Rotations of range[L..R] that we perform. After performing these rotations, we need to find element at a given index.
Example -
Input : arr[] : {1, 2, 3, 4, 5}
ranges[] = { {0, 2}, {0, 3} }
index : 1
Output : 3
Explanation : After first given rotation {0, 2}
arr[] = {3, 1, 2, 4, 5}
After second rotation {0, 3}
arr[] = {4, 3, 1, 2, 5}
After all rotations we have element 3 at given
index 1. Approach -
In first method we rotate array with given condition so time is very high. In this method we change the value of index according to array rotation.
Implementation -
#include<iostream>
using namespace std;
int findvalue(int arr[],int n,int rotation,int range[][2],int index)
{
for(int i=rotation-1;i>=0;i--){
int left=range[i][0];
int right=range[i][1];
if (left <= index && right >= index) {
if(index==left)
index=right;
else
index--;
}
}
return arr[index];
}
int main()
{
int n;
cout<<"Enter the number of elements : ";cin>>n;
int arr[n];
cout<<"Enter elements : "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
int rotation;
cout<<"Ënter the number of rotation : ";cin>>rotation;
int range[rotation][2];
for(int i=0;i<rotation;i++){
cout<<"Range "<<i+1<<" : ";
cin>>range[i][0];
cin>>range[i][1];
}
int index;
cout<<"Enter index : ";cin>>index;
int value=findvalue(arr,n,rotation,range,index);
cout<<endl<<"Value is : "<<value<<endl;
}
Time complexity - O(n)
Space - O(1)
Comments
Post a Comment