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 indexjto the next letter (e.g., 'a'โ'b', 'z'โ'a')previousCost[j]- cost to shift letter at alphabet indexjto 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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code