Minimum Number of Steps to Make Two Strings Anagram II Problem
#2186
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2186.
You are given two strings s and t. In one step, you can append any character to either s or t.
Return the minimum number of steps to make s and t anagrams of each other.
An anagram of a string is a string that contains the same characters with a different (or the same) ordering.
Example 1:
Input: s = "leetcode", t = "coats"
Output: 7
Explanation:
- In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcodeas".
- In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coatsleede".
"leetcodeas" and "coatsleede" are now anagrams of each other.
We used a total of 2 + 5 = 7 steps.
It can be shown that there is no way to make them anagrams of each other with less than 7 steps.
Example 2:
Input: s = "night", t = "thing"
Output: 0
Explanation: The given strings are already anagrams of each other. Thus, we do not need any further steps.
Constraints:
1 <= s.length, t.length <= 2 * 10^5sandtconsist of lowercase English letters.
Solution
Approach: Letter Count Difference
We may append characters to either string, so every letter whose counts differ in s and t needs exactly that many appended characters. Count the letters of s, subtract the letters of t, and sum the absolute values of the 26 differences.
Complexity: O(m + n) time and O(1) extra space (26 counters).
from collections import Counter
class Solution:
def minSteps(self, s: str, t: str) -> int:
cnt = Counter(s)
for c in t:
cnt[c] -= 1
return sum(abs(v) for v in cnt.values())