Minimum Number of Steps to Make Two Strings Anagram Problem
Description
LeetCode Problem 1347.
You are given two strings of the same length 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.
Example 1:
Input: s = "bab", t = "aba"
Output: 1
Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.
Example 2:
Input: s = "leetcode", t = "practice"
Output: 5
Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.
Example 3:
Input: s = "anagram", t = "mangaar"
Output: 0
Explanation: "anagram" and "mangaar" are anagrams.
Constraints:
1 <= s.length <= 5 * 10^4s.length == t.lengthsandtconsist of lowercase English letters only.
Solution
Approach: Counting Letters
Characters of t that can be matched with a character of s can stay. Every other character of t has to be replaced, and one replacement fixes one of them, because s and t have the same length: for each extra letter in t, some letter is missing from t, and the replacement turns one into the other.
So count the letters of s in an array need of 26 entries. Then go through t and decrease the count of each letter. When a count goes below 0, t has more of that letter than s does, so that character must be replaced: add one step.
In Example 2, t = "practice" keeps t, c and e (all in "leetcode"), and the other five letters p, r, a, i, c are surplus, so the answer is 5.
Complexity: O(n) time and O(1) extra space (26 counters).
class Solution:
def minSteps(self, s: str, t: str) -> int:
need = [0] * 26 # letters of s not yet matched by t
for c in s:
need[ord(c) - ord("a")] += 1
steps = 0
for c in t:
i = ord(c) - ord("a")
need[i] -= 1
if need[i] < 0:
steps += 1 # t has one more of this letter than s: replace it
return steps