KatInterview

Fewest Edits to a Repeating Palindromic Pattern

StringsAuto-graded · 25 test cases
MediumAuto-gradedStringsstringspalindromeperiodicity

Last updated

Find the minimum character edits so a string becomes both a palindrome and a repetition of a length-k block, by grouping positions into forced-equal classes.

You are given a lowercase string text of length n and a positive integer period, where n is an exact multiple of period.

In one edit you may replace any single character of text with any lowercase letter. You want to end up with a string result of the same length that satisfies both rules:

  1. Palindrome: result[j] == result[n - 1 - j] for every valid j.
  2. Repeating pattern: result[j] == result[j + period] for every j where j + period < n. In other words, result is one block of period characters repeated n / period times.

Return the smallest number of edits needed to turn text into such a string.

Notes

  • Only the number of edits is returned, not the resulting string.
  • A string that already satisfies both rules needs 0 edits.
  • When period is odd, the middle position of each block mirrors onto itself, so it forms a group on its own and must not be counted twice.

Constraints

  • 2 <= n <= 2 * 10^5
  • 1 <= period < n
  • n % period == 0
  • text contains only lowercase English letters (a-z).

Examples

Example 1

Input: min_edits_periodic_palindrome('abca', 2)

Output: 2

Example 2

Input: min_edits_periodic_palindrome('abcabc', 3)

Output: 2

Example 3

Input: min_edits_periodic_palindrome('aabbcc', 2)

Output: 4

Hints

Hint 1

The repeating rule means every position with the same index modulo `period` must end up with the same letter. Start by thinking of each residue as one unit.

Hint 2

Because `n` is a multiple of `period`, the mirror of position `j` has residue `period - 1 - (j % period)`. So residue `r` and residue `period - 1 - r` must also match, which merges residues into pairs (or a single self-paired middle residue when `period` is odd).

Hint 3

Each merged group is independent of the others. Inside a group, keep the most frequent letter and edit the rest, so the group costs `group_size - max_letter_count`. Sum this over all groups.