KatInterview

Minimum Edits to Form Palindromic Segments

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringstwo-pointerspalindromegreedy

Last updated

Tests two-pointer logic and palindrome verification to compute the fewest replacements that transform every fixed-size segment into a palindrome.

You receive a string text made up of lowercase English letters and an integer block_size.

Divide text into consecutive, non-overlapping segments, each exactly block_size characters long. The length of text is guaranteed to be a multiple of block_size, so the division is exact and leaves no remainder.

In one operation, you may replace any single character in text with any other lowercase English letter. Segment boundaries remain fixed throughout.

Return the smallest number of replacements needed so that every segment becomes a palindrome.

Constraints

  • 1 ≤ block_size ≤ len(text) ≤ 200,000
  • len(text) % block_size == 0
  • text contains only lowercase English letters ('a' through 'z')

Examples

Example 1

Input: min_edits_palindrome_segments('abcbadeba', 3)

Output: 3

Example 2

Input: min_edits_palindrome_segments('racecarannaana', 7)

Output: 1

Example 3

Input: min_edits_palindrome_segments('aaaa', 2)

Output: 0

Hints

Hint 1

Each segment can be made palindromic independently; changes in one segment do not affect any other.

Hint 2

Within a single segment of length k, use two pointers starting at opposite ends and moving inward. Count how many mirrored pairs differ.

Hint 3

When the two characters at mirrored positions do not match, exactly one replacement is required to make them equal.