Skip to content

2381. Shifting Letters II 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  string shiftingLetters(string s, vector<vector<int>>& shifts) {
    int currShift = 0;
    vector<int> timeline(s.length() + 1);

    for (const vector<int>& shift : shifts) {
      const int start = shift[0];
      const int end = shift[1];
      const int direction = shift[2];
      const int diff = direction ? 1 : -1;
      timeline[start] += diff;
      timeline[end + 1] -= diff;
    }

    for (int i = 0; i < s.length(); ++i) {
      currShift = (currShift + timeline[i]) % 26;
      const int num = (s[i] - 'a' + currShift + 26) % 26;
      s[i] = 'a' + num;
    }

    return s;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public String shiftingLetters(String s, int[][] shifts) {
    StringBuilder sb = new StringBuilder();
    int currShift = 0;
    int[] timeline = new int[s.length() + 1];

    for (int[] shift : shifts) {
      final int start = shift[0];
      final int end = shift[1];
      final int direction = shift[2];
      final int diff = direction == 1 ? 1 : -1;
      timeline[start] += diff;
      timeline[end + 1] -= diff;
    }

    for (int i = 0; i < s.length(); ++i) {
      currShift = (currShift + timeline[i]) % 26;
      final int num = (s.charAt(i) - 'a' + currShift + 26) % 26;
      sb.append((char) ('a' + num));
    }

    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def shiftingLetters(self, s: str, shifts: list[list[int]]) -> str:
    ans = []
    currShift = 0
    timeline = [0] * (len(s) + 1)

    for start, end, direction in shifts:
      diff = 1 if direction else -1
      timeline[start] += diff
      timeline[end + 1] -= diff

    for i, c in enumerate(s):
      currShift = (currShift + timeline[i]) % 26
      num = (string.ascii_lowercase.index(c) + currShift + 26) % 26
      ans.append(chr(ord('a') + num))

    return ''.join(ans)