Minimum Number of Steps to Make Two Strings Anagram II - Frequency map

Description

Solution: Two Frequency Arrays

Use two arrays of size 26 to store the frequency of each character in s and t.
Return the sum of the absolute differences between each sFreq[i] and tFreq[i].

n = s.length, m = t.length
Time Complexity: O(n + m)
Space Complexity: O(1)

var minSteps = function(s, t) {
  let sFreq = Array(26).fill(0), tFreq = Array(26).fill(0);
  for (let char of s) sFreq[char.charCodeAt() - 97]++;
  for (let char of t) tFreq[char.charCodeAt() - 97]++;
  let ans = 0;
  for (let i = 0; i < 26; i++) {
    ans += Math.abs(sFreq[i] - tFreq[i]);
  }
  return ans;
};

javascript

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]