Queries for rotation and Kth character of the given string in constant time | C ++ implementation of the approach ; Function to perform the required queries on the given string ; Pointer pointing to the current starting character of the string ; For every query ; If the query is to rotate the string ; Update the pointer pointing to the starting character of the string ; Index of the kth character in the current rotation of the string ; Print the kth character ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define size  2 NEW_LINE void performQueries ( string str , int n , int queries [ ] [ size ] , int q ) { int ptr = 0 ; for ( int i = 0 ; i < q ; i ++ ) { if ( queries [ i ] [ 0 ] == 1 ) { ptr = ( ptr + queries [ i ] [ 1 ] ) % n ; } else { int k = queries [ i ] [ 1 ] ; int index = ( ptr + k - 1 ) % n ; cout << str [ index ] << " STRNEWLINE " ; } } } int main ( ) { string str = " abcdefgh " ; int n = str . length ( ) ; int queries [ ] [ size ] = { { 1 , 2 } , { 2 , 2 } , { 1 , 4 } , { 2 , 7 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; performQueries ( str , n , queries , q ) ; return 0 ; }