Problem Description
Given a string word of length n and an integer k such that k divides n, the goal is to make word k-periodic (i.e. equal to s concatenated T times for some string s of length k) with the minimum number of operations. In one operation, you may choose any two positions (which are multiples of k) and copy the block of k characters from one position into the other.
Key Insights
- The string is divided into T = n/k blocks, each of length k.
- To have a k-periodic string, all blocks must be identical.
- In an operation, you can replace one block with another block that already appears as a candidate.
- The optimal strategy is to choose the block that appears most frequently as the candidate template.
- The minimum number of operations equals the total number of blocks minus the maximum frequency of any block.
Space and Time Complexity
Time Complexity: O(n) — We process each character once while grouping blocks. Space Complexity: O(n/k) — We store the frequency of each of the T blocks.
Solution
We can solve this problem by first splitting the word into T blocks of length k. Then, we count the frequency of each unique block. The candidate block to use is the one that appears the most; hence, the minimum number of operations needed is T minus the frequency of that candidate block. This strategy is valid because every operation copies one block into another, and we can always copy from an already “correct” block once it is set.