Here’s the question link on Leetcode 1347. Minimum Number of Steps to Make Two Strings Anagram:
https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/description
Contents
Brute Force – Frequency Counting
We can count the frequency of every character in both strings.
Then, compare their frequencies. Whenever t has fewer occurrences of a character than s, it needs that many replacements.
class Solution {
public:
int minSteps(string s, string t) {
vector<int> freqS(26, 0), freqT(26, 0);
for(int i = 0; i < s.size(); i++) {
freqS[s[i] - 'a']++;
freqT[t[i] - 'a']++;
}
int ans = 0;
for(int i = 0; i < 26; i++) {
if(freqS[i] > freqT[i]) {
ans += freqS[i] - freqT[i];
}
}
return ans;
}
};
Optimal – Single Frequency Array
We don’t actually need two frequency arrays.
Since we only need to know which characters are missing from t, we can use a single array.
- Increment the count for every character in
s. - Decrement the count for every character in
t. - Positive counts tell us how many characters are missing from
t.
class Solution {
public:
int minSteps(string s, string t) {
vector<int> freq(26, 0);
for(int i = 0; i < s.size(); i++) {
freq[s[i] - 'a']++;
freq[t[i] - 'a']--;
}
int ans = 0;
for(int count : freq) {
if(count > 0) {
ans += count;
}
}
return ans;
}
};
1347. Minimum Number of Steps to Make Two Strings Anagram 1347. Minimum Number of Steps to Make Two Strings Anagram