Permutation Difference between Two Strings Problem
#3146
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3146.
You are given two strings s and t such that every character occurs at most once in s and t is a permutation of s.
The permutation difference between s and t is defined as the sum of the absolute difference between the index of the occurrence of each character in s and the index of the occurrence of the same character in t.
Return the permutation difference between s and t.
Example 1:
Input: s = "abc", t = "bac"
Output: 2
Explanation:
For s = "abc" and t = "bac", the permutation difference of s and t is equal to the sum of:
- The absolute difference between the index of the occurrence of "a" in s and the index of the occurrence of "a" in t.
- The absolute difference between the index of the occurrence of "b" in s and the index of the occurrence of "b" in t.
- The absolute difference between the index of the occurrence of "c" in s and the index of the occurrence of "c" in t.
That is, the permutation difference between s and t is equal to |0 - 1| + |1 - 0| + |2 - 2| = 2.
Example 2:
Input: s = "abcde", t = "edbac"
Output: 12
Explanation: The permutation difference between s and t is equal to |0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12.
Constraints:
1 <= s.length <= 26- Each character occurs at most once in
s. tis a permutation ofs.sconsists only of lowercase English letters.
Solution
Approach: Array of Positions
Store the position of every letter of s in an array d of length 26. Then walk through t and add up |d[c] - i| for the letter c at position i of t.
Complexity: O(n) time and O(1) extra space (26 counters), where n is the length of s.
class Solution:
def findPermutationDifference(self, s: str, t: str) -> int:
d = {c: i for i, c in enumerate(s)}
return sum(abs(d[c] - i) for i, c in enumerate(t))