Shift Distance Between Two Strings - Problem

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:

  • Shift 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.
  • Shift 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.

Input & Output

Example 1 — Basic Transformation
$ Input: s = "abc", t = "bcd", nextCost = [1,1,1,1,...], previousCost = [1,1,1,1,...]
Output: 3
💡 Note: Transform 'a'→'b' (cost 1), 'b'→'c' (cost 1), 'c'→'d' (cost 1). Total cost = 3
Example 2 — Wraparound Case
$ Input: s = "za", t = "ab", nextCost = [1,1,1,...], previousCost = [2,2,2,...]
Output: 3
💡 Note: Transform 'z'→'a' (cost 1 forward), 'a'→'b' (cost 1 forward). Total cost = 2
Example 3 — Choose Backward Path
$ Input: s = "ab", t = "ba", nextCost = [10,10,...], previousCost = [1,1,...]
Output: 2
💡 Note: For 'a'→'b': backward path cheaper. For 'b'→'a': backward path cheaper. Total cost using backward = 2

Constraints

  • 1 ≤ s.length == t.length ≤ 105
  • s and t consist only of lowercase English letters
  • nextCost.length == previousCost.length == 26
  • 1 ≤ nextCost[i], previousCost[i] ≤ 106

Visualization

Tap to expand
Shift Distance: Transform "ab" to "ba"abSource String sbaTarget String tEach character can shift forward or backwardabczyxwvChoose minimum cost path for each transformation
Understanding the Visualization
1
Input Strings
Source string s and target string t with cost arrays
2
Character Transformation
For each position, find cheaper path (forward vs backward)
3
Minimum Total Cost
Sum of all optimal character transformation costs
Key Takeaway
🎯 Key Insight: The alphabet forms a circle - sometimes going backward or wrapping around is cheaper than the direct forward path
Asked in
Google 35 Microsoft 28 Amazon 22
34.6K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen