DEV Community

codingpineapple
codingpineapple

Posted on

1 1

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more