Skip to content

1737. Change Minimum Characters to Satisfy One of Three Conditions 👎

  • Time: $O(|\texttt{a}| + |\texttt{b}|)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
 public:
  int minCharacters(string a, string b) {
    const int m = a.length();
    const int n = b.length();
    vector<int> countA(26);
    vector<int> countB(26);

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

    for (const char c : b)
      ++countB[c - 'a'];

    int ans = INT_MAX;
    int prevA = 0;  // the number of characters in a <= c
    int prevB = 0;  // the number of characters in b <= c

    for (char c = 'a'; c <= 'z'; ++c) {
      // the condition 3
      ans = min(ans, m + n - countA[c - 'a'] - countB[c - 'a']);
      // the conditions 1 and 2
      if (c > 'a')
        ans = min({ans, m - prevA + prevB, n - prevB + prevA});
      prevA += countA[c - 'a'];
      prevB += countB[c - 'a'];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
  public int minCharacters(String a, String b) {
    final int m = a.length();
    final int n = b.length();
    int[] countA = new int[26];
    int[] countB = new int[26];

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

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

    int ans = Integer.MAX_VALUE;
    int prevA = 0; // the number of characters in a <= c
    int prevB = 0; // the number of characters in b <= c

    for (char c = 'a'; c <= 'z'; ++c) {
      // the condition 3
      ans = Math.min(ans, m + n - countA[c - 'a'] - countB[c - 'a']);
      // the conditions 1 and 2
      if (c > 'a')
        ans = Math.min(ans, Math.min(m - prevA + prevB, n - prevB + prevA));
      prevA += countA[c - 'a'];
      prevB += countB[c - 'a'];
    }

    return ans;
  }
}