#1347. Minimum Number of Steps to Make Two Strings Anagram
function minSteps(s, t) {
const counts = new Array(26).fill(0)
for (let i = 0; i < s.length; i++) {
counts[s.charCodeAt(i) - 'a'.charCodeAt(0)]++
counts[t.charCodeAt(i) - 'a'.charCodeAt(0)]--
}
let res = 0
for (let count of counts) {
if (count > 0) res += count
}
return res
}
Firstly, we create a counts
array of the 26 english alphabets i.e. The array have keys from 0 to 25 and each key have value of 0.
Next we loop through the first string s
and for every alphabet denoted by 0 to 25 in the counts array, we increment the value if the character in s
string corresponds to it. We also decrement the value of the same character if it corresponds to the character in the second string t
.
This is what I mean:
for (let i = 0; i < s.length; i++) {
counts[s.charCodeAt(i) - 'a'.charCodeAt(0)]++
counts[t.charCodeAt(i) - 'a'.charCodeAt(0)]--
}
character code of a = 97, b = 98, c = 99 ... z = 122.
s.charCodeAt(i) - 'a'.charCodeAt(0)
When we do this subtraction, we 0 for a, 1 for b ... 25 for z. Any character that corresponds with a will get incremented by one if it is in the s
string also get decremented by one if it is in the t
string.
After this, we loop through the counts array to look for keys whose values are greater than 0, then we add it to the res
variable and return it as our answer.
This corresponds to the number of alphabets we can change to make both strings anagram.