Minimum Number of Steps to Make Two Strings Anagram II - Problem

Given two strings s and t, you need to find the minimum number of character additions to make them anagrams of each other.

In each step, you can append any character to either string s or string t. Your goal is to transform both strings so they contain exactly the same characters with the same frequencies.

What is an anagram? An anagram is a rearrangement of characters from one word to form another word using all characters exactly once. For example, "listen" and "silent" are anagrams.

Example: If s = "leetcode" and t = "coats", we need to add characters to make them anagrams. The optimal solution requires adding specific characters to balance the character frequencies between both strings.

Input & Output

example_1.py โ€” Basic Example
$ Input: s = "leetcode", t = "coats"
โ€บ Output: 7
๐Ÿ’ก Note: We need to add 'l', 'e', 'e', 't', 'd' to t and 'a', 's' to s to make them anagrams. Total additions = 5 + 2 = 7.
example_2.py โ€” Already Anagrams
$ Input: s = "night", t = "thing"
โ€บ Output: 0
๐Ÿ’ก Note: The strings are already anagrams of each other, so no additions are needed.
example_3.py โ€” One Empty String
$ Input: s = "a", t = ""
โ€บ Output: 1
๐Ÿ’ก Note: We need to add 'a' to string t to make both strings anagrams.

Constraints

  • 1 โ‰ค s.length, t.length โ‰ค 5 ร— 104
  • s and t consist of lowercase English letters only
  • Follow up: Can you solve this in O(1) space complexity?

Visualization

Tap to expand
String s"leetcode"l:1 e:3 t:1c:1 o:1 d:1String t"coats"c:1 o:1 a:1t:1 s:1Character Differencesl: |1-0| = 1e: |3-0| = 3d: |1-0| = 1a: |0-1| = 1s: |0-1| = 1others: 0Total: 1+3+1+1+1 = 7Answer7 รท 2 = 3
Understanding the Visualization
1
Inventory Count
Count how many of each character we have in both strings
2
Calculate Imbalance
For each character, find the absolute difference between the two counts
3
Sum Total Deficit
Add up all the imbalances to get the total character deficit
4
Optimize Distribution
Since we can add to either string, we need half the total deficit
Key Takeaway
๐ŸŽฏ Key Insight: The minimum steps needed is half the sum of absolute character frequency differences, because we can strategically add characters to either string to balance them optimally.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.5K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen