Minimum Number of Steps to Make Two Strings Anagram II — LeetCode 2186 Python Solution

MediumHash TableStringCounting
Problem
#2186
Pattern
Hash Map
Reading time
2 min

The problem

You are given two strings s and t. In one step, you can append any character to either s or t.

Example

Input
s = "leetcode", t = "coats"
Output
7
Explanation
- In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcodeas".

Python solution

Python
class Solution:
    def minSteps(self, s: str, t: str) -> int:
        cnt = Counter(s)
        for c in t:
            cnt[c] -= 1
        return sum(abs(v) for v in cnt.values())

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2186. Minimum Number of Steps to Make Two Strings Anagram II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2186. Minimum Number of Steps to Make Two Strings Anagram II?
LeetCode 2186. Minimum Number of Steps to Make Two Strings Anagram II is rated Medium on LeetCode.
What is the time complexity of LeetCode 2186. Minimum Number of Steps to Make Two Strings Anagram II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2186. Minimum Number of Steps to Make Two Strings Anagram II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2186. Minimum Number of Steps to Make Two Strings Anagram II cover?
LeetCode 2186. Minimum Number of Steps to Make Two Strings Anagram II is tagged Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview