Similar Problems

Similar Problems not available

Orderly Queue - Leetcode Solution

Companies:

LeetCode:  Orderly Queue Leetcode Solution

Difficulty: Hard

Topics: math string sorting  

Problem Description: We have a string S of lowercase letters, and an integer array shifts. We want to shift every occurrence of letter S[i], by shifts[i] positions. After we do this, we have a new string where every occurrence of S[i] is shifted by shifts[i] positions. We then want to take the final string and move the first letter of it to the end of the string, repeating this operation K times in total. Return the final string after such manipulation.

Solution: This problem can be solved by iteratively applying the shifts and rotations in a single pass. We keep track of the total shift applied so far and update it with the current shift as we scan each character from the end of the string to the beginning. We perform the rotation of the first character after all the shifts have been applied.

Algorithm:

  1. Initialize a variable "total_shift" to 0.
  2. Iterate the shifts array from the end, and do the following a. Update "total_shift" with the current shift value b. Calculate the shift required for the current character using "total_shift" and the length of the alphabet (26). c. Apply the shift to the current character using ASCII values to convert to and from integers. Store the shifted character in a buffer array.
  3. Perform the rotation K times by moving the first character of the buffer array to the end.
  4. Concatenate the buffer array into a single string and return it as the final result.

Time Complexity: The solution has a time complexity of O(n), where n is the length of the string S.

Space Complexity: The solution has a space complexity of O(n), where n is the length of the string S, as we need to store the shifted characters in a buffer array.

Code:

class Solution { public: string shiftingLetters(string S, vector<int>& shifts) { int n = S.size(); vector<char> buffer(n); int total_shift = 0;

    for(int i=n-1; i>=0; i--) {
        total_shift = (total_shift + shifts[i]) % 26;
        int shift = (S[i] - 'a' + total_shift) % 26;
        buffer[i] = (shift + 'a');
    }

    for(int k=0; k<K; k++) {
        char temp = buffer[0];
        for(int i=1; i<n; i++) {
            buffer[i-1] = buffer[i];
        }
        buffer[n-1] = temp;
    }

    string result(buffer.begin(), buffer.end());
    return result;
}

};

Orderly Queue Solution Code

1