You are given two strings s and t of the same length, and two integer arrays nextCost and previousCost.
In one operation, you can pick any index i of s, and perform either one of the following actions:
s[i] to the next letter in the alphabet. If s[i] == 'z', you should replace it with 'a'. This operation costs nextCost[j] where j is the index of s[i] in the alphabet.s[i] to the previous letter in the alphabet. If s[i] == 'a', you should replace it with 'z'. This operation costs previousCost[j] where j is the index of s[i] in the alphabet.The shift distance is the minimum total cost of operations required to transform s into t.
Return the shift distance from s to t.
Example 1:
Input: s = "abab", t = "baba", nextCost = [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], previousCost = [1,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: 2
Explanation:
i = 0 and shift s[0] 25 times to the previous character for a total cost of 1.i = 1 and shift s[1] 25 times to the next character for a total cost of 0.i = 2 and shift s[2] 25 times to the previous character for a total cost of 1.i = 3 and shift s[3] 25 times to the next character for a total cost of 0.Example 2:
Input: s = "leet", t = "code", nextCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], previousCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
Output: 31
Explanation:
i = 0 and shift s[0] 9 times to the previous character for a total cost of 9.i = 1 and shift s[1] 10 times to the next character for a total cost of 10.i = 2 and shift s[2] 1 time to the previous character for a total cost of 1.i = 3 and shift s[3] 11 times to the next character for a total cost of 11.
Constraints:
1 <= s.length == t.length <= 105s and t consist only of lowercase English letters.nextCost.length == previousCost.length == 260 <= nextCost[i], previousCost[i] <= 109Problem Overview: You are given two strings s and t of the same length. Each character can be shifted forward or backward in the alphabet with different costs. The goal is to compute the minimum total cost required to transform s into t character by character.
Approach 1: Greedy with Prefix Sum Cost Lookup (O(n) time, O(1) space)
Each position in the string can be solved independently. For a character s[i], you can either shift forward through the alphabet until reaching t[i], or shift backward. The key observation is that the alphabet is circular, so forward movement may wrap from 'z' to 'a', and backward movement may wrap in the opposite direction.
To compute shift costs quickly, precompute prefix sums for the forward and backward cost arrays of size 26. A prefix sum lets you calculate the total cost of shifting across a range of characters in constant time. For each index i, calculate the forward cost from s[i] to t[i] and the backward cost using the prefix arrays, then choose the minimum. Iterate through the entire string once and accumulate the result. This greedy decision works because shifts for different indices do not interact.
This approach relies heavily on efficient cumulative cost queries, which makes prefix sum preprocessing ideal. The overall scan of the strings keeps the runtime linear while memory usage remains constant because the alphabet size is fixed.
Approach 2: Dynamic Programming for Cost Optimization (O(n + 26^2) time, O(26^2) space)
A dynamic programming formulation can precompute the minimum cost to shift between every pair of letters. Treat each alphabet character as a node and transitions as shifting forward or backward with the given costs. A DP table dp[a][b] stores the minimum cost to convert character a into character b.
Build this table by simulating forward and backward movements around the alphabet while accumulating costs. Since the alphabet size is fixed (26), the preprocessing is small and predictable. Once the table is built, iterate through the strings and sum dp[s[i]][t[i]] for each position.
This approach is slightly more general and easier to reason about when modeling the alphabet as a transition graph. It still runs efficiently because the preprocessing work is bounded by the constant alphabet size. The strings themselves are processed in linear time.
Recommended for interviews: The greedy + prefix sum solution is what interviewers usually expect. It shows you recognize that each character transformation is independent and that prefix sums allow constant‑time range cost queries. Explaining the dynamic programming formulation also demonstrates strong problem modeling skills with string transformations and cost transitions over a small array domain.
In this approach, for each character in the string s, we compute the character's position in the alphabet (0-indexed). We do the same for string t. For each position, calculate the cost to shift from one character to the other in both clockwise and anti-clockwise directions. We select the minimum of these two costs and add it to the total cost. This provides the minimal cost needed to transform string s to string t.
In this C solution, we iterate over each character of the strings s and t. We calculate both the forward shift and the backward shift to check which transformation is cheaper. The minimum cost for each index is accumulated into cost, which we return as the shift distance.
Time Complexity: O(n), where n is the length of string s. Each character transformation is analyzed in constant time.
Space Complexity: O(1), since no additional data structures are used apart from variable storage.
To minimize costs using dynamic programming, we can track previously computed minimal costs for transformation, helping us decide more efficiently at each step. The idea is to maintain arrays that store cumulative shift costs to convert s[i] to t[i]. By leveraging previously calculated minimal operations, we avoid redundant computations, optimizing the process further for large inputs.
This C solution uses a dynamic programming approach by setting up two arrays to keep track of the minimal forward and backward shift costs for each position in a circular manner around the alphabet. By iterating through and updating these dynamic arrays for each index of s, we efficiently determine the minimal cost paths to form t.
Time Complexity: O(n * 26) due to computing costs for each possible position of the alphabet per character in s.
Space Complexity: O(26) = O(1), given fixed-length auxiliary arrays.
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Greedy Approach for Minimum Cost Calculation | Time Complexity: O(n), where n is the length of string |
| Dynamic Programming for Cost Optimization | Time Complexity: O(n * 26) due to computing costs for each possible position of the alphabet per character in |
| Default Approach | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy with Prefix Sum Cost Lookup | O(n) | O(1) | Best general solution when characters can be processed independently and fast cost lookup is needed |
| Dynamic Programming over Alphabet Transitions | O(n + 26^2) | O(26^2) | Useful when modeling shifts as transitions and precomputing minimum cost between all letter pairs |
Leetcode Biweekly Contest 144 | 3361. Shift Distance Between Two Strings | Codefod • CodeFod • 381 views views
Watch 5 more video solutions →Practice Shift Distance Between Two Strings with our built-in code editor and test cases.
Practice on FleetCode