LeetCode 3361: Shift Distance Between Two Strings Solution
Master LeetCode problem 3361 (Shift Distance Between Two Strings), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3361. Shift Distance Between Two Strings
Problem Explanation
Explanation:
- We can solve this problem by iterating through each character in the strings
sandtand calculating the minimum cost to shift the character fromsto the corresponding character int. - For each character, we consider the cost of shifting to the next character in the alphabet and the cost of shifting to the previous character in the alphabet. We choose the minimum cost of the two.
- We accumulate the total cost over all characters and return this as the shift distance.
Algorithm:
- Initialize a variable
shiftDistanceto store the total shift distance. - Iterate over each character in the strings
sandt. - Calculate the cost of shifting the character to the next character and the cost of shifting to the previous character.
- Update the
shiftDistancewith the minimum cost. - Return the
shiftDistance.
Time Complexity: O(n), where n is the length of the strings s and t.
Space Complexity: O(1)
:
Solution Code
class Solution {
public int shiftDistance(String s, String t, int[] nextCost, int[] previousCost) {
int shiftDistance = 0;
for (int i = 0; i < s.length(); i++) {
int sIdx = s.charAt(i) - 'a';
int tIdx = t.charAt(i) - 'a';
int nextShiftCost = Math.min(nextCost[sIdx], previousCost[tIdx]);
int prevShiftCost = Math.min(previousCost[sIdx], nextCost[tIdx]);
shiftDistance += Math.min(nextShiftCost, prevShiftCost);
}
return shiftDistance;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3361 (Shift Distance Between Two Strings)?
This page provides optimized solutions for LeetCode problem 3361 (Shift Distance Between Two Strings) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3361 (Shift Distance Between Two Strings)?
The time complexity for LeetCode 3361 (Shift Distance Between Two Strings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3361 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3361 in Java, C++, or Python.