Queries for rotation and Kth character of the given string in constant time | Python3 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
size = 2 NEW_LINE def performQueries ( string , n , queries , q ) : NEW_LINE INDENT ptr = 0 ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT if ( queries [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT ptr = ( ptr + queries [ i ] [ 1 ] ) % n ; NEW_LINE DEDENT else : NEW_LINE INDENT k = queries [ i ] [ 1 ] ; NEW_LINE index = ( ptr + k - 1 ) % n ; NEW_LINE print ( string [ index ] ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abcdefgh " ; NEW_LINE n = len ( string ) ; NEW_LINE queries = [ [ 1 , 2 ] , [ 2 , 2 ] , [ 1 , 4 ] , [ 2 , 7 ] ] ; NEW_LINE q = len ( queries ) ; NEW_LINE performQueries ( string , n , queries , q ) ; NEW_LINE DEDENT