Minimum Number of Operations to Make Word K-Periodic - Problem

You're given a string word of length n and an integer k where k divides n evenly. Your goal is to transform the string into a k-periodic string using the minimum number of operations.

What is a k-periodic string? A string is k-periodic if it can be formed by repeating the same substring of length k multiple times. For example, "ababab" is 2-periodic because it repeats "ab" three times.

Operation allowed: You can pick any two indices i and j that are both divisible by k, then replace the substring word[i..i+k-1] with the substring word[j..j+k-1].

Example: If word = "abcdef" and k = 2, you can replace "ab" (at index 0) with "ef" (at index 4) to get "efcdef".

Return the minimum number of operations needed to make the string k-periodic.

Input & Output

example_1.py โ€” Basic case
$ Input: word = "leetcodeleet", k = 4
โ€บ Output: 1
๐Ÿ’ก Note: We can divide the string into 3 segments: ["leet", "code", "leet"]. The pattern "leet" appears twice, so we need 1 operation to change "code" to "leet".
example_2.py โ€” Already periodic
$ Input: word = "ababab", k = 2
โ€บ Output: 0
๐Ÿ’ก Note: The string is already 2-periodic with pattern "ab" repeated 3 times. No operations needed.
example_3.py โ€” All different segments
$ Input: word = "abcdef", k = 2
โ€บ Output: 2
๐Ÿ’ก Note: We have segments ["ab", "cd", "ef"]. All are different, so we need 2 operations to make them all the same (keep one, change the other two).

Visualization

Tap to expand
String: "leetcodeleet" (k=4)leetcodeleetFrequency Map"leet": 2"code": 1Most frequent: "leet" (count=2)Operations = 3 total - 2 max = 1
Understanding the Visualization
1
Divide into Segments
Split the string into equal segments of length k
2
Count Frequencies
Count how many times each unique segment appears
3
Find Optimal Pattern
The most frequent segment should be our target pattern
4
Calculate Operations
Operations needed = Total segments - Max frequency
Key Takeaway
๐ŸŽฏ Key Insight: The optimal target pattern is always the most frequently occurring k-length substring - this minimizes the number of changes needed!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the string, each substring operation takes O(k) time

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map stores at most n/k unique substrings, each of length k

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค word.length โ‰ค 105
  • 1 โ‰ค k โ‰ค word.length
  • k divides word.length
  • word consists only of lowercase English letters
Asked in
Google 42 Amazon 35 Meta 28 Microsoft 22
24.7K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen