Skip to main content

Shift Distance Between Two Strings - Video Solutions

MediumArrayStringPrefix Sum

Leetcode Biweekly Contest 144 | 3361. Shift Distance Between Two Strings | Codefod

CodeFod
11:15391 views
6 video solutions available

Shift Distance Between Two Strings - Video Solution

Watch 6 video solutions for Shift Distance Between Two Strings, a medium level problem involving Array, String, Prefix Sum. This walkthrough by CodeFod has 391 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.

Problem Statement

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.

 

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:

  • We choose index i = 0 and shift s[0] 25 times to the previous character for a total cost of 1.
  • We choose index i = 1 and shift s[1] 25 times to the next character for a total cost of 0.
  • We choose index i = 2 and shift s[2] 25 times to the previous character for a total cost of 1.
  • We choose index 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:

  • We choose index i = 0 and shift s[0] 9 times to the previous character for a total cost of 9.
  • We choose index i = 1 and shift s[1] 10 times to the next character for a total cost of 10.
  • We choose index i = 2 and shift s[2] 1 time to the previous character for a total cost of 1.
  • We choose index i = 3 and shift s[3] 11 times to the next character for a total cost of 11.

 

Constraints:

  • 1 <= s.length == t.length <= 105
  • s and t consist only of lowercase English letters.
  • nextCost.length == previousCost.length == 26
  • 0 <= nextCost[i], previousCost[i] <= 109
Read full problem with examples

Approach Overview

Problem 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.

Complexity Analysis

ApproachTimeSpaceWhen to Use
Greedy with Prefix Sum Cost LookupO(n)O(1)Best general solution when characters can be processed independently and fast cost lookup is needed
Dynamic Programming over Alphabet TransitionsO(n + 26^2)O(26^2)Useful when modeling shifts as transitions and precomputing minimum cost between all letter pairs