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

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "abc", t = "cde"
Output: 4
💡 Note: String s has 'a' and 'b' that t doesn't have. String t has 'd' and 'e' that s doesn't have. We need to add 'd' and 'e' to s, and add 'a' and 'b' to t, totaling 4 steps.
Example 2 — Partial Overlap
$ Input: s = "leetcode", t = "practice"
Output: 11
💡 Note: s has: l(1), e(4), t(1), c(1), o(1), d(1). t has: p(1), r(1), a(1), c(2), t(1), i(1), e(1). Character frequency differences: |1-0|+|4-1|+|1-1|+|1-2|+|1-0|+|1-0|+|0-1|+|0-1|+|0-1|+|0-1| = 1+3+0+1+1+1+1+1+1+1 = 11 steps.
Example 3 — Same Strings
$ Input: s = "anagram", t = "anagram"
Output: 0
💡 Note: Both strings are already anagrams of each other, so no steps are needed.

Constraints

  • 1 ≤ s.length, t.length ≤ 5 × 104
  • s and t consist of lowercase English letters only

Visualization

Tap to expand
Minimum Steps to Make Two Strings Anagram II INPUT String s = "abc" a b c String t = "cde" c d e Character Counts Char s t a 1 0 b 1 0 c 1 1 d 0 1 e 0 1 ALGORITHM STEPS 1 Count chars in s freq[char]++ for each char 2 Count chars in t freq[char]-- for each char 3 Calculate difference Sum |freq[char]| for all 4 Return total steps Each diff needs 1 append Difference Calculation: a: |1-0| = 1 (add 'a' to t) b: |1-0| = 1 (add 'b' to t) c: |1-1| = 0 (balanced) d: |0-1| = 1 (add 'd' to s) e: |0-1| = 1 FINAL RESULT After appending characters: s becomes: "abcde" a b c d e t becomes: "cdeab" c d e a b = Added characters Output: 4 [OK] Both are anagrams! Total steps: 2 + 2 = 4 Key Insight: Use frequency array to track character differences between strings s and t. Increment for s chars, decrement for t chars. Sum of absolute differences = minimum steps. Time: O(n+m) | Space: O(26) = O(1) where n, m are lengths of s and t. TutorialsPoint - Minimum Number of Steps to Make Two Strings Anagram II | Optimal Solution
Asked in
Facebook 15 Google 12 Microsoft 8
28.5K Views
Medium Frequency
~12 min Avg. Time
892 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