#2381

Shifting Letters II

Medium
ArrayStringPrefix SumPrefix SumDifference Array
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of applying shifts directly, we can track the cumulative effect of shifts using a difference array. This allows us to compute the final shifts in a single pass, making the solution much more efficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a shift array initialized to zero, with the same length as the string.
  2. 2Step 2: For each shift operation, update the start index with +1 and the index after the end with -1 to mark the beginning and end of shifts.
  3. 3Step 3: Compute the prefix sum on the shift array to determine the total shifts for each index.
  4. 4Step 4: Apply the computed shifts to the original string, adjusting for the wrap-around using modulo 26.
solution.py14 lines
1def shiftingLetters(s, shifts):
2    n = len(s)
3    shift = [0] * (n + 1)
4    for start, end, direction in shifts:
5        shift[start] += 1 if direction == 1 else -1
6        if end + 1 < n:
7            shift[end + 1] -= 1 if direction == 1 else -1
8    for i in range(1, n):
9        shift[i] += shift[i - 1]
10    result = []
11    for i in range(n):
12        new_char = chr((ord(s[i]) - ord('a') + shift[i]) % 26 + ord('a'))
13        result.append(new_char)
14    return ''.join(result)

Complexity note: This complexity arises because we make a single pass to mark shifts and another pass to compute the final characters, leading to O(n) time overall.

  • 1Using a difference array allows us to efficiently track cumulative shifts.
  • 2Prefix sums can simplify the application of multiple range updates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.