Skip to content

Commit f56944b

Browse files
committed
O(n) time to build hashmap and O(26) space for building Hashmap
1 parent a70b5f5 commit f56944b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.
3+
4+
Return the minimum number of steps to make t an anagram of s.
5+
6+
An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.
7+
8+
9+
10+
Example 1:
11+
12+
Input: s = "bab", t = "aba"
13+
Output: 1
14+
Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.
15+
Example 2:
16+
17+
Input: s = "leetcode", t = "practice"
18+
Output: 5
19+
Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.
20+
Example 3:
21+
22+
Input: s = "anagram", t = "mangaar"
23+
Output: 0
24+
Explanation: "anagram" and "mangaar" are anagrams.
25+
26+
27+
Constraints:
28+
29+
1 <= s.length <= 5 * 104
30+
s.length == t.length
31+
s and t consist of lowercase English letters only.
32+
"""
33+
class Solution:
34+
def minSteps(self, s: str, t: str) -> int:
35+
counter_s = collections.Counter(s)
36+
counter_t = collections.Counter(t)
37+
return sum([val - counter_t[key] if val > counter_t[key] else 0 for key,val in counter_s.items()])

0 commit comments

Comments
 (0)