DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 1347. Minimum Number of Steps to Make Two Strings Anagram (javascript)

Description:

Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character.

Return the minimum number of steps to make t an anagram of s.

An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

Solution:

Time Complexity : O(n)
Space Complexity: O(1)

var minSteps = function(s, t) {
    // Array to hold the counts of each letter
    const counts = new Array(26).fill(0);

    // Add counts of each letter to the array
    // zero = no difference, positive or negative count = count difference between the two strings for a particular
    for (let i = 0; i < s.length; i++) {
        counts[t.charCodeAt(i) - 97]++;
        counts[s.charCodeAt(i) - 97]--;
    }

    let output = 0;

    // Add the letter count differences together
    for (let i = 0; i < 26; i++) {
        if (counts[i] > 0) output += counts[i];
    }

    return output;
};
Enter fullscreen mode Exit fullscreen mode

Discussion (0)