#2186

Minimum Number of Steps to Make Two Strings Anagram II

Medium
Hash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses character frequency counts to determine how many characters need to be added to each string. This approach is efficient because it only requires a single pass through each string to count characters, followed by a comparison of counts.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each character in both strings using a HashMap.
  2. 2Step 2: For each unique character in both strings, calculate the absolute difference in counts.
  3. 3Step 3: Sum these differences to get the total number of steps required.
solution.py13 lines
1# Full working Python code
2from collections import Counter
3
4def min_steps(s, t):
5    count_s = Counter(s)
6    count_t = Counter(t)
7    steps = 0
8    for char in set(count_s.keys()).union(set(count_t.keys())):
9        steps += abs(count_s[char] - count_t[char])
10    return steps
11
12# Example usage
13print(min_steps('leet tco de', 'co a t s'))  # Output: 7

Complexity note: This complexity is linear because we only traverse each string once to count characters, and then we perform a constant-time operation for each unique character.

  • 1Character frequency is key to determining how many characters need to be added.
  • 2Using a HashMap allows efficient counting and comparison of character frequencies.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.