Minimum Edits for Palindromic Fixed-Size Blocks

Medium · Coding & Algorithms · Software Engineer · HR Screen

Problem Statement

Implement a function that computes the fewest single-character edits needed to turn every fixed-width segment of a string into a palindrome:

def min_changes_to_palindromic_blocks(password: str, k: int) -> int:

You receive a lowercase ASCII string password and a positive integer k that evenly divides len(password). Partition password into consecutive, disjoint segments of width k starting at indices 0, k, 2 * k, .... Segment boundaries are fixed in place and cannot shift.

In one edit, you may overwrite any character in password with any lowercase letter from 'a' to 'z'. Return the minimum total number of edits required so that every length-k segment reads the same left-to-right and right-to-left.

Examples

Example 1

Input:  password = "levelstare", k = 5
Output: 2

Walk-through: Splitting into width-5 segments gives "level" and "stare". "level" is already a palindrome (0 edits). In "stare", outer pair ('s', 'e') and inner pair ('t', 'r') both differ while center 'a' mirrors itself, requiring 2 edits (for instance "stats"). Total: 0 + 2 = 2.

Example 2

Input:  password = "deeduvwxkzzx", k = 4
Output: 3

Walk-through: The three width-4 segments are "deed", "uvwx", and "kzzx": - "deed" has matching pairs ('d', 'd') and ('e', 'e') (0 edits). - "uvwx" has mismatched pairs ('u', 'x') and ('v', 'w') (2 edits, e.g. "uvvu"). - "kzzx" has mismatched outer pair ('k', 'x') and matching inner pair ('z', 'z') (1 edit, e.g. "kzzk").

Total edits: 0 + 2 + 1 = 3.

Example 3

Input:  password = "rotorcivic", k = 5
Output: 0

Walk-through: Both width-5 segments ("rotor" and "civic") are already palindromes, so 0 edits are needed.

Constraints

  • 1 <= k <= len(password) <= 2 * 10^5
  • len(password) % k == 0
  • password contains only lowercase English letters ('a'–'z').

Step-by-step walkthrough

  1. Understand the blocks and the goal

    We are given a lowercase string password and an integer k that divides len(password) evenly. The string is cut into fixed, non-overlapping blocks of length k:

    password = "deeduvwxkzzx",  k = 4
    
    Index:    0  1  2  3 | 4  5  6  7 | 8  9 10 11
    Blocks:  [d  e  e  d] [u  v  w  x] [k  z  z  x]
              block 0      block 1      block 2
    

    In one move, we can replace any character with any lowercase letter ('a' to 'z'). We want the fewest replacements so that every block on its own is a palindrome — a string that reads identically from left to right and from right to left (such as "aba" or "abba").

    Watch out for a common misreading: the entire password does not need to be a palindrome, and being a whole-string palindrome does not make the blocks palindromes either. For example, "abccba" is a palindrome overall, yet for k = 2 its blocks are "ab", "cc", "ba", which require 2 changes (turning "ab" into "aa" and "ba" into "bb").

  2. Why blocks can be solved one at a time

    Because block boundaries cannot move and blocks never overlap, changing a character at index p only alters the single block containing p — it has zero effect on any other block.

    That independence means there is never a trade-off between two blocks. The minimum total cost for the whole password is simply the sum of the minimum costs of each individual k-letter block.

  3. Key idea: one change per mismatched mirror pair

    Now zoom in on a single block of length k. Imagine folding the block in half so its left end touches its right end:

    Even block (k = 4):              Odd block (k = 5):
      index:  0   1   2   3            index:  0   1   2   3   4
      chars:  a   b   c   d            chars:  a   b   c   d   e
              |   |___|   |                    |   |   ^   |   |
              |___________|                    |   |  free |   |
                                               |   |_______|   |
      2 mirror pairs: (0,3), (1,2)             |_______________|
                                         2 mirror pairs: (0,4), (1,3); index 2 mirrors itself
    

    A block is a palindrome if and only if every mirrored pair (left, right) holds the same letter. Moreover, different mirror pairs never share an index, so each pair can be fixed independently:

    • Same letter (password[left] == password[right]): Already matches -> 0 changes.
    • Different letters (password[left] != password[right]): At least one of the two slots must change, so it takes at least 1 change. Overwriting password[right] with password[left] (or vice versa) makes them equal in exactly 1 change. Changing both to some third letter would cost 2 changes, which is strictly worse.
    • Middle slot when k is odd (left == right): A single middle letter always equals itself -> 0 changes.

    Therefore, the minimum changes for one block equals the number of mismatched mirror pairs inside that block.

  4. Count mismatches inside one block with two pointers

    We can count mismatched pairs inside password[block_start : block_start + k] using two pointers — two integer index variables left and right that start at opposite ends of the block and step inward toward each other on each iteration.

    def count_block_mismatches(password: str, block_start: int, k: int) -> int:
        """Count how many mirrored character pairs differ inside password[block_start : block_start + k]."""
        mismatches = 0
        # Two pointers starting at the left and right ends of this k-character block.
        left = block_start
        right = block_start + k - 1
    
        # Use strict '<' because when k is odd, left == right at the exact center character,
        # which mirrors itself and never needs to be changed.
        while left < right:
            if password[left] != password[right]:
                # Replacing either character to match the other fixes this mirror pair in 1 change.
                mismatches += 1
            left += 1
            right -= 1
    
        return mismatches
    

    Notice two clean details: - Using while left < right handles k = 1 automatically (left == right right away, so the loop runs 0 times and returns 0). - Indexing directly into password avoids allocating a substring slice for every block, keeping extra memory O(1).

  5. Sum across all blocks and trace the examples

    The blocks start at indices 0, k, 2k, ..., which we iterate with range(0, len(password), k):

    def min_changes_to_palindromic_blocks(password: str, k: int) -> int:
        # Blocks are disjoint and fixed at indices [0..k-1], [k..2k-1], ...,
        # so the minimum total changes is the sum of minimum changes for each block independently.
        total_changes = 0
    
        for block_start in range(0, len(password), k):
            total_changes += count_block_mismatches(password, block_start, k)
    
        return total_changes
    

    Let's trace the three examples:

    Example 1: password = "levelstare", k = 5
      Block 0 [0..4] = "level": ('l','l') match, ('e','e') match, center 'v' skipped -> 0
      Block 1 [5..9] = "stare": ('s','e') mismatch (+1), ('t','r') mismatch (+1), center 'a' skipped -> 2
      Total = 0 + 2 = 2
    
    Example 2: password = "deeduvwxkzzx", k = 4
      Block 0 [0..3]  = "deed": ('d','d') match, ('e','e') match -> 0
      Block 1 [4..7]  = "uvwx": ('u','x') mismatch (+1), ('v','w') mismatch (+1) -> 2
      Block 2 [8..11] = "kzzx": ('k','x') mismatch (+1), ('z','z') match -> 1
      Total = 0 + 2 + 1 = 3
    
    Example 3: password = "rotorcivic", k = 5
      Block 0 [0..4] = "rotor": ('r','r'), ('o','o') -> 0
      Block 1 [5..9] = "civic": ('c','c'), ('i','i') -> 0
      Total = 0
    
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_block_mismatches(password: str, block_start: int, k: int) -> int:
        """Count how many mirrored character pairs differ inside password[block_start : block_start + k]."""
        mismatches = 0
        # Two pointers starting at the left and right ends of this k-character block.
        left = block_start
        right = block_start + k - 1
    
        # Use strict '<' because when k is odd, left == right at the exact center character,
        # which mirrors itself and never needs to be changed.
        while left < right:
            if password[left] != password[right]:
                # Replacing either character to match the other fixes this mirror pair in 1 change.
                mismatches += 1
            left += 1
            right -= 1
    
        return mismatches
    
    
    def min_changes_to_palindromic_blocks(password: str, k: int) -> int:
        # Blocks are disjoint and fixed at indices [0..k-1], [k..2k-1], ...,
        # so the minimum total changes is the sum of minimum changes for each block independently.
        total_changes = 0
    
        for block_start in range(0, len(password), k):
            total_changes += count_block_mismatches(password, block_start, k)
    
        return total_changes
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

A palindrome is a string that reads the exact same forward and backward, like "deed" or "level". Imagine cutting the password into fixed strips of length k and folding each strip in half so its left end touches its right end. Because the strips do not overlap, changing a letter on one strip never affects any other strip. On each folded strip, every pair of letters that touch each other must match: if they already match, we do nothing; if they differ, repainting either one of the two letters to match its partner fixes that pair in exactly 1 change.

A naive brute-force search that tries all 26 replacement letters at each position would explore 26^n candidate strings, which is completely infeasible for n = 200,000. Even trying all 26 letters for each pair does 26x unnecessary work because picking a third letter different from both originals always costs 2 changes instead of 1. Instead, we use two pointers (two index variables starting at opposite ends of a block and moving inward) to count mismatched mirror pairs directly in one pass.

For example, take password = "deeduvwxkzzx" with k = 4: 1. Split into three length-4 blocks: "deed", "uvwx", and "kzzx". 2. In "deed", both mirror pairs ('d', 'd') and ('e', 'e') already match (0 changes). 3. In "uvwx", outer letters 'u' and 'x' differ (+1) and inner letters 'v' and 'w' differ (+1), for 2 changes; in "kzzx", outer 'k' and 'x' differ (+1) while inner 'z' and 'z' match (0), for 1 change. 4. Adding the independent block costs gives 0 + 2 + 1 = 3 total changes.

Complexity

Let n = len(password).

  • Time: O(n). There are n / k disjoint blocks, and inside each block the two pointers step inward k // 2 times doing an O(1) character comparison per step, for at most n // 2 comparisons in total.
  • Space: O(1) extra space. We only store a few integer indices and counters (block_start, left, right, mismatches, total_changes) and never allocate substring slices.

Edge cases

  • k = 1: Every 1-character block is already a palindrome; left < right starts False and the function immediately returns 0.
  • k = len(password): The whole password is a single block, so we count mismatched mirror pairs across the entire string.
  • Odd k: The center character of every block (left == right) pairs with itself and never requires a replacement.
  • Whole string is a palindrome, blocks are not: Input "abccba" with k = 2 has blocks "ab", "cc", "ba", correctly returning 2 rather than 0.
  • Already valid blocks: Every mirror pair matches, returning 0.
  • Maximum size (n = 200,000): At most 100,000 character comparisons run in a few milliseconds in Python.

Common mistakes

  • Mirroring across the entire string (i vs n - 1 - i) instead of within each block (block_start + i vs block_start + k - 1 - i): That makes the whole password a palindrome rather than making each length-k block a palindrome.
  • Looping offset across the full range(k) instead of range(k // 2) (or left < right): Comparing from index 0 all the way to k - 1 visits every mirror pair from both sides and double-counts the answer.
  • Charging 2 changes for a mismatch: Only one of the two mirrored positions needs to be overwritten to match the other.
  • Assuming blocks can shift or wrap around: The problem fixes block boundaries at multiples of k (0, k, 2k, ...).

Follow-up questions

  • How does the algorithm change if every length-k segment must not only be a palindrome, but also equal the exact same string across all segments? Now offset i and its mirror offset k - 1 - i inside every segment are all forced to hold one shared letter. For each offset i with 0 <= i <= (k - 1) // 2, collect all characters at block_start + i (and block_start + k - 1 - i when i != k - 1 - i) across all n // k segments into one bucket of size m, count each letter's frequency in that bucket, keep the highest frequency max_count, and add m - max_count edits. Since every index in password belongs to one bucket and each bucket inspects at most 26 counts, total time stays O(n) with O(1) auxiliary space.
  • Suppose the palindrome requirement applies to every sliding window of length k instead of non-overlapping segments. How would you compute the minimum edits? A sliding window checks every contiguous k-character slice password[p : p + k] for p = 0, 1, ..., n - k. When k = 1 the answer is 0, and when n == k there is only one window (our single-block answer). Whenever n > k and k >= 2, adjacent windows couple indices two steps apart: mirroring across window p and then across window p + 1 shifts any position by +2, forcing s[0] == s[2] == s[4] == ... and s[1] == s[3] == s[5] == .... If k is even, mirroring inside a window also links even positions to odd positions, forcing all n characters to share one letter (n - max_letter_count); if k is odd, even and odd indices never mix, so the string alternates like "ababab..." with minimum edits (even_count - max_even_letter) + (odd_count - max_odd_letter), computed in O(n) time.
  • If replacing letter x with letter y incurs a directed weight table[x][y] rather than a flat cost of 1, how do you minimize the total cost? Mirrored pairs remain independent, yet converting both x = password[left] and y = password[right] to a third letter t can beat x -> y or y -> x (for instance, if table['a']['b'] = 10 whereas table['a']['c'] = 1 and table['b']['c'] = 1, meeting at 'c' costs 2). Precompute best_pair[x][y] = min over all 26 letters t of (table[x][t] + table[y][t]) (with table[c][c] = 0) in 26^3 = 17,576 operations upfront, then sum best_pair[password[left]][password[right]] over every mirror pair in O(26^3 + n) time. If multi-hop rewrites like 'a' -> 'd' -> 'b' are permitted at one index, first run Floyd-Warshall (a 26^3 dynamic programming algorithm that computes shortest paths between all pairs of letters in a weighted graph) on table before computing best_pair.

Follow-up questions

Similar questions

More Citadel interview questions

All 90 Citadel questions →