LeetCode Problem - Link

Problem

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


Sequential Approach

Pretty easy to solve, I realize that my approach is slower than the majority of the solutions because I've introduced variables to keep track of what's happening in the code for better readability. Not the fastest, but is readable for sure.


/**
 * @param {string} s
 * @param {string} t
 * @return {number}
 */
var findPermutationDifference = function (s, t) {
    var map_s = {}
    var map_t = {}


    // Build maps
    map_s = build_map(s)
    map_t = build_map(t)


    var count = 0;
    for (var i = 0; i < s.length; i++) {
        var letter = s[i]


        // Get indexes from the maps we've built
        var map_s_index = map_s[letter]
        var map_t_index = map_t[letter]


        // Get absolute difference between the indexes and append to count
        var diff = Math.abs(map_s[letter] - map_t_index)
        count += diff
    }
    return count


};


var build_map = (arr) => {
    // A function that builds map of indexes of a character and returns it
    var map = {}
    for (let i = 0; i < arr.length; i++) {
        if (!map[i]) {
            map[arr[i]] = i
        }
    }
    return map
}