Skip to content

1347. Minimum Number of Steps to Make Two Strings Anagram 👍

  • 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
16
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(count.begin(), count.end(), 0, [](int subtotal, int c) {
      return subtotal + abs(c);
    }) / 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int minSteps(String s, String t) {
    int[] count = new int[26];

    for (final char c : s.toCharArray())
      ++count[c - 'a'];

    for (final char c : t.toCharArray())
      --count[c - 'a'];

    return Arrays.stream(count).map(Math::abs).sum() / 2;
  }
}
1
2
3
4
5
class Solution:
  def minSteps(self, s: str, t: str) -> int:
    count = collections.Counter(s)
    count.subtract(collections.Counter(t))
    return sum(abs(value) for value in count.values()) // 2