Skip to content

3137. Minimum Number of Operations to Make Word K-Periodic 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int minimumOperationsToMakeKPeriodic(string word, int k) {
    unordered_map<string, int> count;
    int maxFreq = 0;

    for (int i = 0; i < word.length(); i += k)
      ++count[word.substr(i, k)];

    for (const auto& [_, freq] : count)
      maxFreq = max(maxFreq, freq);

    return word.length() / k - maxFreq;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public int minimumOperationsToMakeKPeriodic(String word, int k) {
    Map<String, Integer> count = new HashMap<>();

    for (int i = 0; i < word.length(); i += k)
      count.merge(word.substring(i, i + k), 1, Integer::sum);

    final int maxFreq = count.values().stream().max(Integer::compare).orElse(0);
    return word.length() / k - maxFreq;
  }
}
1
2
3
4
class Solution:
  def minimumOperationsToMakeKPeriodic(self, word: str, k: int) -> int:
    count = collections.Counter(word[i:i + k] for i in range(0, len(word), k))
    return len(word) // k - max(count.values())