#3137

Minimum Number of Operations to Make Word K-Periodic

Medium
Hash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal approach, we count the frequency of each k-length substring that starts at indices divisible by k. The minimum operations needed will be the total number of substrings minus the frequency of the most common substring.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a frequency map to count occurrences of each k-length substring starting at indices divisible by k.
  2. 2Step 2: Find the maximum frequency from the frequency map.
  3. 3Step 3: Calculate the minimum operations as the total number of k-length substrings minus the maximum frequency.
solution.py10 lines
1from collections import defaultdict
2
3def min_operations(word, k):
4    freq = defaultdict(int)
5    n = len(word)
6    for i in range(0, n, k):
7        freq[word[i:i + k]] += 1
8    max_freq = max(freq.values())
9    total_substrings = n // k
10    return total_substrings - max_freq

Complexity note: This complexity is linear because we only traverse the string once to build the frequency map and then once more to find the maximum frequency.

  • 1Understanding the frequency of substrings helps minimize operations.
  • 2The most common substring dictates how many changes are needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.