Minimum Number of Operations to Make Word K-Periodic - Problem
You are given a string word of size n, and an integer k such that k divides n.
In one operation, you can pick any two indices i and j that are divisible by k, then replace the substring of length k starting at i with the substring of length k starting at j. That is, replace the substring word[i..i + k - 1] with the substring word[j..j + k - 1].
Return the minimum number of operations required to make word k-periodic.
We say that word is k-periodic if there is some string s of length k such that word can be obtained by concatenating s an arbitrary number of times. For example, if word == "ababab", then word is 2-periodic for s = "ab".
Input & Output
Example 1 — Basic Case
$
Input:
word = "ababcb", k = 2
›
Output:
1
💡 Note:
Split into segments: ["ab", "ab", "cb"]. "ab" appears 2 times, "cb" appears 1 time. Choose "ab" as target pattern and replace "cb" with "ab". Operations needed: 3 - 2 = 1.
Example 2 — Already K-Periodic
$
Input:
word = "abab", k = 2
›
Output:
0
💡 Note:
Split into segments: ["ab", "ab"]. All segments are already identical, so 0 operations needed.
Example 3 — All Different
$
Input:
word = "abcd", k = 1
›
Output:
3
💡 Note:
Split into segments: ["a", "b", "c", "d"]. Each appears once. Choose any as target (say "a") and replace the other 3. Operations: 4 - 1 = 3.
Constraints
- 1 ≤ word.length ≤ 105
- 1 ≤ k ≤ word.length
- k divides word.length
- word consists only of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Word "ababcb" with k=2
2
Split into Segments
Divide word into k-length pieces
3
Find Pattern
Choose most frequent segment as target
4
Calculate Operations
Count replacements needed
Key Takeaway
🎯 Key Insight: Choose the most frequent k-length pattern to minimize replacement operations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code