Perform String Shifts

Updated on 10 July, 2025
Perform String Shifts header image

Problem Statement

In this task, you are provided with a string s composed of lowercase English letters. Alongside the string, you receive a list of operations known as shift, where each operation is represented by a pair [direction, amount]. The direction can either be 0, indicating a left shift, or 1, indicating a right shift. The amount represents how many positions the string should be shifted in the specified direction.

  • A left shift (direction = 0) moves the first character of the string to its end.
  • A right shift (direction = 1) moves the last character of the string to the beginning.

The goal is to determine the resultant string after applying all the shift operations specified in shift.

Examples

Example 1

Input:

s = "abc", shift = [[0,1],[1,2]]

Output:

"cab"

Explanation:

 
[0,1] means shift to left by 1. "abc" -> "bca"
[1,2] means shift to right by 2. "bca" -> "cab"

Example 2

Input:

s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]

Output:

"efgabcd"

Explanation:

 
[1,1] means shift to right by 1. "abcdefg" -> "gabcdef"
[1,1] means shift to right by 1. "gabcdef" -> "fgabcde"
[0,2] means shift to left by 2. "fgabcde" -> "abcdefg"
[1,3] means shift to right by 3. "abcdefg" -> "efgabcd"

Constraints

  • 1 <= s.length <= 100
  • s only contains lower case English letters.
  • 1 <= shift.length <= 100
  • shift[i].length == 2
  • directioniis either 0 or 1.
  • 0 <= amounti <= 100

Approach and Intuition

To solve this problem efficiently, we must understand the properties of string shifting:

  1. Reduction of Redundant Shifts:

    • Performing a left shift followed by a right shift of the same amount essentially brings the string back to its original configuration. Similarly, consecutive shifts in the same direction can be combined into a single operation.
  2. Steps:

    1. Calculate Net Shifts:
      • Iterate over each operation in shift. Sum up all the amounts for left shifts and right shifts separately.
    2. Determine Effective Shift:
      • Compute the net effect of all shifts by subtracting the total amount of left shifts from the total amount of right shifts. This gives a single value that indicates the net number of positions the string needs to be shifted and in which direction.
    3. Modulo Operation:
      • Since shifting a string by its length returns it to the initial state, use the modulo operation (net_shift % len(s)) to reduce the total shift to a meaningful value.
    4. Perform the Shift:
      • If the net effect is positive, perform a right shift; if negative, perform a left shift using the computed effective shift value.
  3. Edge Case Handling:

    • If s has only one character or the net shift is zero after modulo reduction, the output will be s itself, as no effective shifting is possible.

By following these steps, we can transform the sequence of operations into a single effective operation, thus optimizing the shifting process.

Solutions

  • C++
cpp
class Solution {
public:
    string rotateString(string str, vector<vector<int>>& operations) {
        int totalShifts = 0;
        for (auto& op : operations) {
            if (op[0] == 1) {
                op[1] *= -1;
            }
            totalShifts += op[1];
        }
    
        int length = str.length();
        totalShifts = ((totalShifts % length) + length) % length;
        str = str.substr(totalShifts) + str.substr(0, totalShifts);
        return str;
    }
};

The provided C++ solution implements a function to perform string shifts based on a set of operations. Each operation specifies the direction and amount of the shift. The solution approaches the problem by first calculating a cumulative shift amount from all operations. It then applies this total shift to the string in an efficient manner without needing to perform each individual operation sequentially.

  • Here's a breakdown of the solution process:
    • Initialize a variable to accumulate the total number of shifts.
    • Iterate through each operation. Depending on the direction specified in the operation (left or right), adjust the shift amount accordingly.
    • Compute the effective shift needed by reducing the total shifts modulo the string's length, considering positive and negative shifts appropriately.
    • Perform the shift on the string using substring operations: the string is divided at the shift point, and the two parts are swapped.

Apply this technique to efficiently manipulate the string based on the sequence of operations, resulting in the final modified string. The use of modulo with string length ensures that the shift is always within the bounds of the string, optimizing performance.

  • Java
java
class Solution {
    
    public String manipulateString(String str, int[][] operations) {
        // Calculate total left shifts; treat right shifts as negative left shifts.
        int totalShifts = 0;
        for (int[] operation : operations) {
            if (operation[0] == 1) {
                operation[1] = -operation[1];
            }
            totalShifts += operation[1];
        }
    
        // Normalize the shifts and perform the operations on the string.
        totalShifts = Math.floorMod(totalShifts, str.length());
        str = str.substring(totalShifts) + str.substring(0, totalShifts);
        return str;
    }
}

This Java-based solution to the given problem "Perform String Shifts" operates by calculating the overall shifts needed on the provided string and then applying these shifts. The method manipulateString in the Solution class executes string modifications based on the input operations.

Here's a brief rundown of how the code works:

  • Initialize a variable totalShifts to accumulate the sum of all shifts.
  • Iterate through the operations array. Each operation consists of two elements: the direction of the shift (0 for left, 1 for right) and the magnitude of the shift.
  • Convert right shifts to negative by negating the shift value when the direction is 1.
  • Add up all the shifts to get totalShifts.
  • Normalize totalShifts using modulo operation with the string length to handle overflows.
  • Perform the shift by using the substring method to rearrange the string according to the calculated shift.
  • Return the shifted string.

This approach ensures efficient string manipulation even with a series of shifting operations, making the algorithm both straightforward and robust.

  • Python
python
class Solution:
    def shiftString(self, content: str, transformations: List[List[int]]) -> str:
        net_shifts = 0
        for direction, units in transformations:
            if direction == 1:
                units = -units
            net_shifts += units
            
        net_shifts %= len(content)
        content = content[net_shifts:] + content[:net_shifts]
        return content

In this solution summary, you learn how to implement string shifts based on transformation rules using Python.

The provided Python function shiftString takes two parameters: a string content and a list of transformation instructions transformations. Each transformation consists of a direction and a number of units. The directions are represented as 0 (left shift) and 1 (right shift).

  • Calculate the effective number of shifts required:

    • Iterate over each transformation.
    • Convert right shifts (direction 1) into equivalent left shifts by changing the sign of the units.
    • Accumulate all shifts into net_shifts.
  • Normalize the total shifts:

    • Use modulo operation with the length of content to ensure shifts don’t exceed the string length, avoiding unnecessary rotations.
  • Perform the shift:

    • Use slicing to rearrange the string based on net_shifts. If net_shifts is positive, move the front part of the string to the end.
    • Concatenate the sliced parts to get the shifted string.

Finally, return the transformed string after applying the cumulative shifts. This method effectively handles both directions for shifts and works efficiently even with a large number of transformation commands by reducing the shifts to a minimum necessary amount using the modulo operation.

Comments

No comments yet.