Skip to content

2287. Rearrange Characters to Make Target String 👍

  • Time: $O(n)$
  • Space: $O(128) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int rearrangeCharacters(string s, string target) {
    int ans = s.length();
    vector<int> countS(128);
    vector<int> countT(128);

    for (const char c : s)
      ++countS[c];

    for (const char c : target)
      ++countT[c];

    for (const char c : target)
      ans = min(ans, countS[c] / countT[c]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int rearrangeCharacters(String s, String target) {
    int ans = s.length();
    int[] countS = new int[128];
    int[] countT = new int[128];

    for (final char c : s.toCharArray())
      ++countS[c];

    for (final char c : target.toCharArray())
      ++countT[c];

    for (final char c : target.toCharArray())
      ans = Math.min(ans, countS[c] / countT[c]);

    return ans;
  }
}
1
2
3
4
5
class Solution:
  def rearrangeCharacters(self, s: str, target: str) -> int:
    countS = collections.Counter(s)
    countT = collections.Counter(target)
    return min(countS[c] // countT[c] for c in target)