LeetCode 3146: Permutation Difference between Two Strings Solution

Master LeetCode problem 3146 (Permutation Difference between Two Strings), a easy 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.

3146. Permutation Difference between Two Strings

Problem Explanation

Explanation

To solve this problem, we can iterate through each character in string s and string t. For each character, we calculate the absolute difference between the index of its occurrence in string s and the index of its occurrence in string t, and sum up these differences to get the permutation difference.

  1. Create a map to store the index of each character in string s.
  2. Iterate through string t.
  3. For each character in t, calculate the absolute difference between its index in s and its index in t.
  4. Sum up these absolute differences to get the permutation difference.

The time complexity of this solution is O(n), where n is the length of the input string s. The space complexity is O(1) since we are using a constant amount of extra space regardless of the input size.

Solution Code

class Solution {
    public int getPermutationDifference(String s, String t) {
        int[] indexMap = new int[26];
        for (int i = 0; i < s.length(); i++) {
            indexMap[s.charAt(i) - 'a'] = i;
        }
        
        int permutationDiff = 0;
        for (int i = 0; i < t.length(); i++) {
            char c = t.charAt(i);
            permutationDiff += Math.abs(indexMap[c - 'a'] - i);
        }
        
        return permutationDiff;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3146 (Permutation Difference between Two Strings)?

This page provides optimized solutions for LeetCode problem 3146 (Permutation Difference 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 3146 (Permutation Difference between Two Strings)?

The time complexity for LeetCode 3146 (Permutation Difference 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 3146 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3146 in Java, C++, or Python.

Back to LeetCode Solutions