#848

Shifting Letters

Medium
ArrayStringPrefix SumPrefix SumArray
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 calculate the total shifts needed for each character in a single pass. This reduces the number of operations significantly and avoids nested loops.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a new array to store the cumulative shifts.
  2. 2Step 2: Traverse the shifts array from the end to the beginning, accumulating the shifts for each character.
  3. 3Step 3: For each character in the string, apply the total shift calculated and convert it back to a character.
solution.py11 lines
1# Full working Python code
2s = 'abc'
3shifts = [3, 5, 9]
4result = []
5total_shift = 0
6for i in range(len(shifts) - 1, -1, -1):
7    total_shift += shifts[i]
8    result.append(chr((ord(s[i]) - ord('a') + total_shift) % 26 + ord('a')))
9result.reverse()
10final_string = ''.join(result)
11print(final_string)

Complexity note: The time complexity is O(n) because we traverse the shifts array once, and the space complexity is O(n) due to the result storage.

  • 1Cumulative shifts allow for efficient calculations.
  • 2Processing from the end of the shifts array simplifies the logic.

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