Shift Distance Between Two Strings - Problem

Imagine you have a magical typewriter where each letter can transform into its neighbors in the alphabet, but each transformation has a different cost! ๐ŸŽญ

You're given two strings s and t of the same length, along with two cost arrays:

  • nextCost[j] - cost to shift letter at alphabet index j to the next letter (e.g., 'a'โ†’'b', 'z'โ†’'a')
  • previousCost[j] - cost to shift letter at alphabet index j to the previous letter (e.g., 'b'โ†’'a', 'a'โ†’'z')

Your mission is to find the minimum total cost to transform string s into string t using these shift operations. The alphabet wraps around, so 'z' can become 'a' and vice versa!

Example: If s = "abc" and t = "bcd", you could shift each character forward once, with total cost being nextCost[0] + nextCost[1] + nextCost[2].

Input & Output

example_1.py โ€” Basic Transformation
$ Input: s = "abc", t = "bcd", nextCost = [1,1,1,...], previousCost = [2,2,2,...]
โ€บ Output: 3
๐Ÿ’ก Note: Transform each character forward once: 'a'โ†’'b' (cost 1), 'b'โ†’'c' (cost 1), 'c'โ†’'d' (cost 1). Total cost = 3.
example_2.py โ€” Circular Wrap Around
$ Input: s = "az", t = "ba", nextCost = [1,1,...,10], previousCost = [10,10,...,1]
โ€บ Output: 2
๐Ÿ’ก Note: For 'a'โ†’'b': forward costs 1. For 'z'โ†’'a': forward costs 10, backward costs 1, so choose backward. Total = 1 + 1 = 2.
example_3.py โ€” Same Characters
$ Input: s = "hello", t = "hello", nextCost = [1,2,3,...], previousCost = [1,2,3,...]
โ€บ Output: 0
๐Ÿ’ก Note: No transformation needed since source and target strings are identical. Total cost = 0.

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
Alphabet CarouselABCDEF...and so onForward PathBackward Path
Understanding the Visualization
1
Set up the carousel
Place source and target characters on the circular alphabet
2
Calculate clockwise cost
Sum up nextCost values going forward around the circle
3
Calculate counterclockwise cost
Sum up previousCost values going backward around the circle
4
Choose optimal path
Select the direction with minimum total transformation cost
Key Takeaway
๐ŸŽฏ Key Insight: In a circular alphabet, there are only 2 paths between any characters - we just calculate both costs and pick the minimum!
Asked in
Google 45 Amazon 38 Meta 25 Microsoft 22
28.5K Views
Medium Frequency
~18 min Avg. Time
847 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