Loading

LeetCode problem#3146

Permutation Difference between Two Strings

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

21 lines
1class Solution {
2    // time O(1) because always O(26) characters
3    // space O(1)
4    public int findPermutationDifference(String s, String t) {
5        // we cannot assume s is sorted in alphabetical order if split into
6        // separate characters, so we have to build an array of their indices.
7        int[] indices = new int[26];
8        for (int i = 0 ; i < s.length(); i++) {
9            indices[s.charAt(i) - 'a'] = i;
10        }
11
12        int sum = 0;
13        for (int i = 0; i < t.length(); i++) {
14            int diff = indices[t.charAt(i) - 'a'] - i;
15            int absoluteDiff = diff < 0 ? -diff : diff;
16            sum += absoluteDiff;
17        }
18
19        return sum;
20    }
21}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.