Skip to content

1427. Perform String Shifts 👍

  • Time: $O(|\texttt{shift}| + |\texttt{s}|)$
  • Space: $O(|\texttt{s}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  string stringShift(string s, vector<vector<int>>& shift) {
    const int n = s.length();
    int move = 0;

    for (const vector<int>& pair : shift) {
      const int direction = pair[0];
      const int amount = pair[1];
      if (direction == 0)
        move -= amount;
      else
        move += amount;
    }

    move = ((move % n) + n) % n;
    return s.substr(n - move) + s.substr(0, n - move);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public String stringShift(String s, int[][] shift) {
    final int n = s.length();
    int move = 0;

    for (int[] pair : shift) {
      final int direction = pair[0];
      final int amount = pair[1];
      if (direction == 0)
        move -= amount;
      else
        move += amount;
    }

    move = ((move % n) + n) % n;
    return s.substring(n - move) + s.substring(0, n - move);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def stringShift(self, s: str, shift: list[list[int]]) -> str:
    move = 0

    for direction, amount in shift:
      if direction == 0:
        move -= amount
      else:
        move += amount

    move %= len(s)
    return s[-move:] + s[:-move]