Skip to content

358. Rearrange String k Distance Apart 👍

  • Time: $O(26n) = O(n)$
  • 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
32
33
34
35
36
37
38
39
40
41
class Solution {
 public:
  string rearrangeString(string s, int k) {
    const int n = s.length();
    string ans;
    vector<int> count(26);
    // valid[i] := the leftmost index ('a' + i) can appear
    vector<int> valid(26);

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

    for (int i = 0; i < n; ++i) {
      const char c = getBestLetter(count, valid, i);
      if (c == '*')
        return "";
      ans += c;
      --count[c - 'a'];
      valid[c - 'a'] = i + k;
    }

    return ans;
  }

 private:
  // Returns the valid letter that has the most count.
  char getBestLetter(const vector<int>& count, const vector<int>& valid,
                     int index) {
    int maxCount = -1;
    char bestLetter = '*';

    for (char c = 'a'; c <= 'z'; ++c)
      if (count[c - 'a'] > 0 && count[c - 'a'] > maxCount &&
          index >= valid[c - 'a']) {
        bestLetter = c;
        maxCount = count[c - 'a'];
      }

    return bestLetter;
  }
};
 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
32
33
34
35
36
37
class Solution {
  public String rearrangeString(String s, int k) {
    final int n = s.length();
    StringBuilder sb = new StringBuilder();
    int[] count = new int[26];
    // valid[i] := the leftmost index character i can appear
    int[] valid = new int[26];

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

    for (int i = 0; i < n; ++i) {
      final char c = getBestLetter(count, valid, i);
      if (c == '*')
        return "";
      sb.append(c);
      --count[c - 'a'];
      valid[c - 'a'] = i + k;
    }

    return sb.toString();
  }

  // Returns the valid letter that has the most count.
  private char getBestLetter(int[] count, int[] valid, int index) {
    int maxCount = -1;
    char bestLetter = '*';

    for (char c = 'a'; c <= 'z'; ++c)
      if (count[c - 'a'] > 0 && count[c - 'a'] > maxCount && index >= valid[c - 'a']) {
        bestLetter = c;
        maxCount = count[c - 'a'];
      }

    return bestLetter;
  }
}
 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
class Solution:
  def rearrangeString(self, s: str, k: int) -> str:
    n = len(s)
    ans = []
    count = collections.Counter(s)
    # valid[i] := the leftmost index i can appear
    valid = collections.Counter()

    def getBestLetter(index: int) -> str:
      """Returns the valid letter that has the most count."""
      maxCount = -1
      bestLetter = '*'

      for c in string.ascii_lowercase:
        if count[c] > 0 and count[c] > maxCount and index >= valid[c]:
          bestLetter = c
          maxCount = count[c]

      return bestLetter

    for i in range(n):
      c = getBestLetter(i)
      if c == '*':
        return ''
      ans.append(c)
      count[c] -= 1
      valid[c] = i + k

    return ''.join(ans)