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^5len(password) % k == 0passwordcontains only lowercase English letters ('a'–'z').
Step-by-step walkthrough
Understand the blocks and the goal
We are given a lowercase string
passwordand an integerkthat divideslen(password)evenly. The string is cut into fixed, non-overlapping blocks of lengthk: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 2In 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 fork = 2its blocks are"ab","cc","ba", which require2changes (turning"ab"into"aa"and"ba"into"bb").Why blocks can be solved one at a time
Because block boundaries cannot move and blocks never overlap, changing a character at index
ponly alters the single block containingp— 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.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 itselfA 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 least1change. Overwritingpassword[right]withpassword[left](or vice versa) makes them equal in exactly 1 change. Changing both to some third letter would cost2changes, which is strictly worse. - Middle slot when
kis 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.
- Same letter (
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 variablesleftandrightthat 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 mismatchesNotice two clean details: - Using
while left < righthandlesk = 1automatically (left == rightright away, so the loop runs0times and returns0). - Indexing directly intopasswordavoids allocating a substring slice for every block, keeping extra memoryO(1).Sum across all blocks and trace the examples
The blocks start at indices
0, k, 2k, ..., which we iterate withrange(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_changesLet'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 = 0Complete 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 aren / kdisjoint blocks, and inside each block the two pointers step inwardk // 2times doing anO(1)character comparison per step, for at mostn // 2comparisons 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 < rightstartsFalseand the function immediately returns0.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"withk = 2has blocks"ab","cc","ba", correctly returning2rather than0. - Already valid blocks: Every mirror pair matches, returning
0. - Maximum size (
n = 200,000): At most100,000character comparisons run in a few milliseconds in Python.
Common mistakes
- Mirroring across the entire string (
ivsn - 1 - i) instead of within each block (block_start + ivsblock_start + k - 1 - i): That makes the whole password a palindrome rather than making each length-kblock a palindrome. - Looping
offsetacross the fullrange(k)instead ofrange(k // 2)(orleft < right): Comparing from index0all the way tok - 1visits every mirror pair from both sides and double-counts the answer. - Charging
2changes 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
iand its mirror offsetk - 1 - iinside every segment are all forced to hold one shared letter. For each offsetiwith0 <= i <= (k - 1) // 2, collect all characters atblock_start + i(andblock_start + k - 1 - iwheni != k - 1 - i) across alln // ksegments into one bucket of sizem, count each letter's frequency in that bucket, keep the highest frequencymax_count, and addm - max_countedits. Since every index inpasswordbelongs to one bucket and each bucket inspects at most 26 counts, total time staysO(n)withO(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 slicepassword[p : p + k]forp = 0, 1, ..., n - k. Whenk = 1the answer is0, and whenn == kthere is only one window (our single-block answer). Whenevern > kandk >= 2, adjacent windows couple indices two steps apart: mirroring across windowpand then across windowp + 1shifts any position by+2, forcings[0] == s[2] == s[4] == ...ands[1] == s[3] == s[5] == .... Ifkis even, mirroring inside a window also links even positions to odd positions, forcing allncharacters to share one letter (n - max_letter_count); ifkis 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 inO(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]andy = password[right]to a third lettertcan beatx -> yory -> x(for instance, iftable['a']['b'] = 10whereastable['a']['c'] = 1andtable['b']['c'] = 1, meeting at'c'costs2). Precomputebest_pair[x][y] = min over all 26 letters t of (table[x][t] + table[y][t])(withtable[c][c] = 0) in26^3 = 17,576operations upfront, then sumbest_pair[password[left]][password[right]]over every mirror pair inO(26^3 + n)time. If multi-hop rewrites like'a' -> 'd' -> 'b'are permitted at one index, first run Floyd-Warshall (a26^3dynamic programming algorithm that computes shortest paths between all pairs of letters in a weighted graph) ontablebefore computingbest_pair.
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?
- Suppose the palindrome requirement applies to every sliding window of length k instead of non-overlapping segments. How would you compute the minimum edits?
- 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?
Similar questions
- Exchange and National Best Quote Aggregator
- Sliding Square Submatrix Sums
- Largest Group Around an Anchor Interval
- Largest Forward Gain in a Sequence
- Lazy-Expiring Session Token Store
- Dynamic Weighted Random Sampler with Updates
More Citadel interview questions
- Optimal Shift Payout with Streak Bonuses Medium
- Multi-Venue Order Book for BBO and NBBO Medium
- Regional Temperature Regressions and Greedy Predictor Selection for NYC Medium Pro
- One-Shot Batch Selection for Labeling 200 of One Million Feature Vectors Medium Pro
- Binary Classification over Variable-Size Point Clouds with Missing Entries Hard Pro
- Exchange and National Best Quote Aggregator Medium Pro
- Sliding Square Submatrix Sums Medium Pro
- Largest Group Around an Anchor Interval Medium Pro
- Navigating a High-Stakes Engineering Obstacle Medium Pro
- Real-Time Telemetry Ingestion and Sub-2s Alerting Engine Medium Pro