Talentd
FleetCode

2186. Minimum Number of Steps to Make Two Strings Anagram II

Medium73.3% acceptance1 company

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 * 105
  • s and t consist of lowercase English letters.

Asked at 1 company

Hints open one at a time

Hint 1
Notice that for anagrams, the order of the letters is irrelevant.
Hint 2
For each letter, we can count its frequency in s and t.
Hint 3
For each letter, its contribution to the answer is the absolute difference between its frequency in s and t.
9:06
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def minSteps(self, s: str, t: str) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
"leetcode"
"coats"
Input
"night"
"thing"
Your code is saved on this device.Solution