Find element at given index after a number of rotations | Java code to rotate an array and answer the index query ; Function to compute the element at given index ; Range [ left ... right ] ; Rotation will not have any effect ; Returning new element ; Driver ; No . of rotations ; Ranges according to 0 - based indexing
import java . util . * ; class GFG { static int findElement ( int [ ] arr , int [ ] [ ] ranges , int rotations , int index ) { for ( int i = rotations - 1 ; i >= 0 ; i -- ) { int left = ranges [ i ] [ 0 ] ; int right = ranges [ i ] [ 1 ] ; if ( left <= index && right >= index ) { if ( index == left ) index = right ; else index -- ; } } return arr [ index ] ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int rotations = 2 ; int [ ] [ ] ranges = { { 0 , 2 } , { 0 , 3 } } ; int index = 1 ; System . out . println ( findElement ( arr , ranges , rotations , index ) ) ; } }