Skip to content

2186. Minimum Number of Steps to Make Two Strings Anagram II 👍

  • Time: $O(|\texttt{s}| + |\texttt{t}|)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int minSteps(string s, string t) {
    vector<int> count(26);

    for (const char c : s)
      ++count[c - 'a'];

    for (const char c : t)
      --count[c - 'a'];

    return accumulate(begin(count), end(count), 0,
                      [](int res, int c) { return res + abs(c); });
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public int minSteps(String s, String t) {
    int[] count = new int[26];
    s.chars().forEach(c -> ++count[c - 'a']);
    t.chars().forEach(c -> --count[c - 'a']);
    return Arrays.stream(count).map(Math::abs).sum();
  }
}
1
2
3
4
5
class Solution:
  def minSteps(self, s: str, t: str) -> int:
    count = collections.Counter(s)
    count.subtract(Counter(t))
    return sum([abs(c) for c in count.values()])