Leetcode 3146: Permutation Difference between Two Strings

grid47
grid47
Exploring patterns and algorithms
Dec 28, 2023 4 min read

You are given two strings, s and t, where every character occurs at most once in both strings and t is a permutation of s. The permutation difference between s and t is defined as the sum of the absolute differences between the index of each character in s and the index of the occurrence of the same character in t. Your task is to compute the permutation difference between s and t.
Problem
Approach
Steps
Complexity
Input: The input consists of two strings `s` and `t`.
Example: Example 1: Input: s = "xys", t = "syx" Output: 2
Constraints:
• 1 <= s.length <= 26
• Each character occurs at most once in `s`.
• t is a permutation of `s`.
• s consists only of lowercase English letters.
Output: Return the permutation difference between `s` and `t`.
Example: Example 1: Input: s = "xys", t = "syx" Output: 2
Constraints:
• The output should be the sum of the absolute differences of character indices in `s` and `t`.
Goal: To compute the permutation difference, iterate over each character in `s` and find the corresponding index in `t`, then calculate the absolute difference in indices.
Steps:
• Iterate through each character in string `s`.
• For each character in `s`, find its index in string `t`.
• Compute the absolute difference between the indices of each character in `s` and `t`.
• Sum these absolute differences and return the result.
Goal: The constraints for the input strings are given below.
Steps:
• 1 <= s.length <= 26
• Each character occurs at most once in `s`.
• t is a permutation of `s`.
• s consists only of lowercase English letters.
Assumptions:
• The input strings `s` and `t` are permutations of each other.
• Each character in `s` and `t` occurs only once.
Input: Example 1:
Explanation: For `s = "abc"` and `t = "bac"`, the permutation difference is the sum of absolute differences between indices of characters: |0 - 1| + |1 - 0| + |2 - 2| = 2.

Input: Example 2:
Explanation: For `s = "abcdef"` and `t = "dfecba"`, the permutation difference is: |0 - 4| + |1 - 3| + |2 - 5| + |3 - 2| + |4 - 1| + |5 - 0| = 12.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus