Magicsheet logo

Minimum Number of Steps to Make Two Strings Anagram II

Medium
100%
Updated 6/1/2025

Asked by 1 Company

Minimum Number of Steps to Make Two Strings Anagram II

1. What is this problem about?

This is a variation of the previous anagram problem, but with a key difference: you can now append characters to either string to make them anagrams. You are given two strings s and t, which may have different lengths. The goal is to find the minimum number of total additions needed so that s and t become anagrams of each other.

2. Why is this asked in interviews?

Companies like Wealthfront use this to see if a candidate can adapt a known solution to slightly different constraints. It tests the ability to handle absolute differences in frequencies across two sets. It's a clean, logical problem that focuses on the "symmetric difference" of character sets, which is a common task in data processing.

3. Algorithmic pattern used

The pattern is Frequency Counting and Absolute Difference. You count the frequency of each character in both s and t. For each character from 'a' to 'z', the number of additions required for that specific character is abs(count_in_s - count_in_t). Summing these absolute differences across all 26 characters gives the total steps.

4. Example explanation

  • s = "leetcode", t = "coats"
  • 'l': 1 in s, 0 in t (diff 1)
  • 'e': 3 in s, 0 in t (diff 3)
  • 't': 1 in s, 1 in t (diff 0)
  • 'c': 1 in s, 1 in t (diff 0)
  • 'o': 1 in s, 1 in t (diff 0)
  • 'd': 1 in s, 0 in t (diff 1)
  • 'a': 0 in s, 1 in t (diff 1)
  • 's': 0 in s, 1 in t (diff 1) Total = 1 + 3 + 1 + 1 + 1 = 7.

5. Common mistakes candidates make

The most common mistake is applying the logic from "Anagram I" (where you only replace characters). In this version, every difference counts as an addition. Another error is neglecting characters that appear in t but not in s. Using a single frequency array and subtracting values can work, but you must ensure you take the absolute value of the final counts.

6. Interview preparation tip

Always clarify if the operation is "replacement," "deletion," or "addition." The logic changes significantly. If the operation is addition or deletion, you are looking for the total count of characters that do not have a pair in the other string. This is essentially the same as finding the size of the symmetric difference of two multisets.

Similar Questions