Python3 Program for Find element at given index after a number of rotations
Last Updated :
05 Sep, 2024
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.
Examples :
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.
Method : Brute-force The brute force approach is to actually rotate the array for all given ranges, finally return the element in at given index in the modified array.
Method : Efficient We can do offline processing after saving all ranges.
Suppose, our rotate ranges are : [0..2] and [0..3]
We run through these ranges from reverse.
After range [0..3], index 0 will have the element which was on index 3.
So, we can change 0 to 3, i.e. if index = left, index will be changed to right.
After range [0..2], index 3 will remain unaffected.
So, we can make 3 cases :
If index = left, index will be changed to right.
If index is not bounds by the range, no effect of rotation.
If index is in bounds, index will have the element at index-1.
Below is the implementation :
For better explanation:-
10 20 30 40 50
Index: 1
Rotations: {0,2} {1,4} {0,3}
Answer: Index 1 will have 30 after all the 3 rotations in the order {0,2} {1,4} {0,3}.
We performed {0,2} on A and now we have a new array A1.
We performed {1,4} on A1 and now we have a new array A2.
We performed {0,3} on A2 and now we have a new array A3.
Now we are looking for the value at index 1 in A3.
But A3 is {0,3} done on A2.
So index 1 in A3 is index 0 in A2.
But A2 is {1,4} done on A1.
So index 0 in A2 is also index 0 in A1 as it does not lie in the range {1,4}.
But A1 is {0,2} done on A.
So index 0 in A1 is index 2 in A.
On observing it, we are going deeper into the previous rotations starting from the latest rotation.
{0,3}
|
{1,4}
|
{0,2}
This is the reason we are processing the rotations in reverse order.
Please note that we are not rotating the elements in the reverse order, just processing the index from reverse.
Because if we actually rotate in reverse order, we might get a completely different answer as in case of rotations the order matters.
C++
#include <iostream>
#include <vector>
// Function to compute the element at given index
int findElement(std::vector<int>& arr, std::vector<std::vector<int>>& ranges, int rotations, int index) {
for (int i = rotations - 1; i >= 0; i--) {
// Range[left...right]
int left = ranges[i][0];
int right = ranges[i][1];
// Rotation will not have any effect
if (left <= index && right >= index) {
if (index == left)
index = right;
else
index--;
}
}
// Returning new element
return arr[index];
}
// Driver Code
int main() {
std::vector<int> arr = {1, 2, 3, 4, 5};
// No. of rotations
int rotations = 2;
// Ranges according to 0-based indexing
std::vector<std::vector<int>> ranges = {{0, 2}, {0, 3}};
int index = 1;
std::cout << findElement(arr, ranges, rotations, index) << std::endl;
return 0;
}
Java
import java.util.ArrayList;
class Main {
// Function to compute the element at the given index
static int findElement(ArrayList<Integer> arr, ArrayList<ArrayList<Integer>> ranges, int rotations, int index) {
for (int i = rotations - 1; i >= 0; i--) {
// Range[left...right]
int left = ranges.get(i).get(0);
int right = ranges.get(i).get(1);
// Rotation will not have any effect
if (left <= index && right >= index) {
if (index == left)
index = right;
else
index--;
}
}
// Returning the new element
return arr.get(index);
}
// Driver Code
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>() {{
add(1);
add(2);
add(3);
add(4);
add(5);
}};
// No. of rotations
int rotations = 2;
// Ranges according to 0-based indexing
ArrayList<ArrayList<Integer>> ranges = new ArrayList<ArrayList<Integer>>() {{
add(new ArrayList<Integer>() {{ add(0); add(2); }});
add(new ArrayList<Integer>() {{ add(0); add(3); }});
}};
int index = 1;
System.out.println(findElement(arr, ranges, rotations, index));
}
}
Python
# Python 3 code to rotate an array
# and answer the index query
# Function to compute the element
# at given index
def findElement(arr, ranges, rotations, index) :
for i in range(rotations - 1, -1, -1 ) :
# Range[left...right]
left = ranges[i][0]
right = ranges[i][1]
# Rotation will not have
# any effect
if (left <= index and right >= index) :
if (index == left) :
index = right
else :
index = index - 1
# Returning new element
return arr[index]
# Driver Code
arr = [ 1, 2, 3, 4, 5 ]
# No. of rotations
rotations = 2
# Ranges according to
# 0-based indexing
ranges = [ [ 0, 2 ], [ 0, 3 ] ]
index = 1
print(findElement(arr, ranges, rotations, index))
# This code is contributed by Nikita Tiwari.
C#
using System;
using System.Collections.Generic;
class Program
{
// Function to compute the element at the given index
static int FindElement(List<int> arr, List<List<int>> ranges, int rotations, int index)
{
for (int i = rotations - 1; i >= 0; i--)
{
// Range[left...right]
int left = ranges[i][0];
int right = ranges[i][1];
// Rotation will not have any effect
if (left <= index && right >= index)
{
if (index == left)
index = right;
else
index--;
}
}
// Returning the new element
return arr[index];
}
// Driver Code
static void Main()
{
List<int> arr = new List<int> { 1, 2, 3, 4, 5 };
// No. of rotations
int rotations = 2;
// Ranges according to 0-based indexing
List<List<int>> ranges = new List<List<int>> { new List<int> { 0, 2 }, new List<int> { 0, 3 } };
int index = 1;
Console.WriteLine(FindElement(arr, ranges, rotations, index));
}
}
JavaScript
function findElement(arr, ranges, rotations, index) {
for (let i = rotations - 1; i >= 0; i--) {
// Range[left...right]
let left = ranges[i][0];
let right = ranges[i][1];
// Rotation will not have any effect
if (left <= index && right >= index) {
if (index === left)
index = right;
else
index--;
}
}
// Returning new element
return arr[index];
}
// Driver Code
const arr = [1, 2, 3, 4, 5];
// No. of rotations
const rotations = 2;
// Ranges according to 0-based indexing
const ranges = [[0, 2], [0, 3]];
const index = 1;
console.log(findElement(arr, ranges, rotations, index));
Output :
3
Time Complexity: O(N), where N represents the given number of rotations.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Please refer complete article on Find element at given index after a number of rotations for more details!
Similar Reads
Python3 Program to Find the Mth element of the Array after K left rotations
Given non-negative integers K, M, and an array arr[] with N elements find the Mth element of the array after K left rotations. Examples: Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1Output: 5Explanation: The array after first left rotation a1[ ] = {4, 5, 23, 3}The array after second left rotation a2[ ]
2 min read
Python3 Program to Find Mth element after K Right Rotations of an Array
[GFGTABS] Python3 # Python3 program to implement # the above approach # Function to return Mth element of # array after k right rotations def getFirstElement(a, N, K, M): # The array comes to original state # after N rotations K %= N # If K is greater or equal to M if (K >= M): # Mth element afte
1 min read
Python3 Program to Generate all rotations of a number
Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits of the number are shifted one position to the left and the digit at the first position is shifted to the last.Examples: Input: n = 123 Output: 231 31
2 min read
Python3 Program to Rotate digits of a given number by K
INTRODUCTION:One important point to consider when working with the algorithm to rotate the digits of a given number by k positions is the time complexity. If we were to implement this algorithm using the approach shown in the previous example, the time complexity would be O(n), where n is the number
4 min read
Python Program to find the Next Nearest element in a Matrix
Given a matrix, a set of coordinates and an element, the task is to write a python program that can get the coordinates of the elements next occurrence. Input : test_list = [[4, 3, 1, 2, 3], [7, 5, 3, 6, 3], [8, 5, 3, 5, 3], [1, 2, 3, 4, 6]], i, j = 1, 3, K = 3 Output : (1, 4) Explanation : After (1
4 min read
Python Program for Find the element that appears once
Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once. Expected time complexity is O(n) and O(1) extra space. Examples : Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3} Output: 2 In the given array all element appear thre
2 min read
Python3 Program for Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string.Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab"
2 min read
Python3 Program to Find Maximum value possible by rotating digits of a given number
Given a positive integer N, the task is to find the maximum value among all the rotations of the digits of the integer N. Examples: Input: N = 657Output: 765Explanation: All rotations of 657 are {657, 576, 765}. The maximum value among all these rotations is 765. Input: N = 7092Output: 9270Explanati
2 min read
Python Program to find minimum number of rotations to obtain actual string
Given two strings s1 and s2. The task is to find out the minimum number of string rotations for the given string s1 to obtain the actual string s2. Examples: Input : eeksg, geeks Output: 1 Explanation: g is rotated left to obtain geeks. Input : eksge, geeks Output: 2 Explanation : e and g are left r
2 min read
Python3 Program to Modify given array to a non-decreasing array by rotation
Given an array arr[] of size N (consisting of duplicates), the task is to check if the given array can be converted to a non-decreasing array by rotating it. If it's not possible to do so, then print "No". Otherwise, print "Yes". Examples: Input: arr[] = {3, 4, 5, 1, 2}Output: YesExplanation: After
3 min read