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. Ifs[i] == 'z'
, you should replace it with'a'
. This operation costsnextCost[j]
wherej
is the index ofs[i]
in the alphabet. - Shift
s[i]
to the previous letter in the alphabet. Ifs[i] == 'a'
, you should replace it with'z'
. This operation costspreviousCost[j]
wherej
is the index ofs[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
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= s.length == t.length <= 10^5
s
andt
consist only of lowercase English letters.nextCost.length == previousCost.length == 26
0 <= nextCost[i], previousCost[i] <= 10^9
Solution
Method 1 – Prefix Sum for Circular Shifts
Intuition
For each character, we can shift forward (next) or backward (previous) in the alphabet, wrapping around. The cost for each shift is given. For each position, we compute the cost to shift from s[i] to t[i] in both directions and take the minimum.
Approach
- For each character pair (s[i], t[i]):
- Compute the forward distance (number of next shifts) and backward distance (number of previous shifts) in the alphabet.
- For each, sum the costs using nextCost and previousCost arrays, using prefix sums for efficiency.
- Take the minimum of the two costs and add to the total.
- Return the total cost.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * 26)
, where n = length of s. For each character, we may sum up to 26 costs. - 🧺 Space complexity:
O(1)
, ignoring input storage, as we use only a few variables and arrays of size 26.