Saturday, January 4, 2025
Google search engine
HomeLanguagesJavascriptJavascript Program for Queries for rotation and Kth character of the given...

Javascript 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. (1, K): Left rotate the string by K characters.
  2. (2, K): Print the Kth character of the string.

Examples: 
 

Input: str = “abcdefgh”, q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} 
Output: 


Query 1: str = “cdefghab” 
Query 2: 2nd character is d 
Query 3: str = “ghabcdef” 
Query 4: 7th character is e
Input: str = “abc”, q[][] = {{1, 2}, {2, 2}} 
Output: 

 

 

Approach: The main observation here is that the string doesn’t need to be rotated in every query instead we can create a pointer ptr pointing to the first character of the string and which can be updated for every rotation as ptr = (ptr + K) % N where K the integer by which the string needs to be rotated and N is the length of the string. Now for every query of the second type, the Kth character can be found by str[(ptr + K – 1) % N].
Below is the implementation of the above approach: 
 

Javascript




<script>
 
// Javascript implementation of the approach
 
var size = 2;
 
// Function to perform the required
// queries on the given string
function performQueries(str, n, queries, q)
{
 
    // Pointer pointing to the current starting
    // character of the string
    var ptr = 0;
 
    // For every query
    for (var i = 0; i < q; i++) {
 
        // If the query is to rotate the string
        if (queries[i][0] == 1) {
 
            // Update the pointer pointing to the
            // starting character of the string
            ptr = (ptr + queries[i][1]) % n;
        }
        else {
 
            var k = queries[i][1];
 
            // Index of the kth character in the
            // current rotation of the string
            var index = (ptr + k - 1) % n;
 
            // Print the kth character
            document.write( str[index] + "<br>");
        }
    }
}
 
// Driver code
var str = "abcdefgh";
var n = str.length;
var queries = [ [ 1, 2 ], [ 2, 2 ],
                        [ 1, 4 ], [ 2, 7 ] ];
var q = queries.length;
performQueries(str, n, queries, q);
 
</script>


Output: 

d
e

 

Time Complexity: O(Q) , Where Q is the number of queries
Auxiliary Space: O(1)

Please refer complete article on Queries for rotation and Kth character of the given string in constant time for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments